【问题标题】:How to update the data source after updating the data grid view in c#c#中更新数据网格视图后如何更新数据源
【发布时间】:2021-05-26 00:01:09
【问题描述】:

我现在正在我的数据网格视图中添加一个删除功能。 我通过代码添加删除按钮,我打算通过Event触发删除功能。

private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        //if click is on new row or header row
        if (e.RowIndex == dataGridView1.NewRowIndex || e.RowIndex < 0)
            return;

        //Check if click is on specific column 
        if (e.ColumnIndex == dataGridView1.Columns["dataGridViewDeleteButton"].Index)
        {
            
            System.Console.WriteLine("delete button pressed!");
            dataGridView1.Rows.RemoveAt(e.RowIndex);

            
        }
    }

我已经测试过这个功能,debug控制台实际上打印出delete button pressed!,表示事件触发成功。 但是,我遇到了一个问题;删除特定行的单元格后如何更新下划线数据源? 数据源代码为:

DataTable dataTable = new DataTable();
// data loading ...

【问题讨论】:

  • 数据源不会自动重新绘制。诀窍是将数据源设置为 null 并返回到原始数据源: dataGridView1.DataSource = null; dataGridView1.DataSource = 数据表;
  • 我在我的项目中测试了你的代码,一切正常,dataTable也会自动更新(删除指定行)。那么,您是否将dataTable 声明为全局变量?
  • 是的,我做到了。我对DataGridView有点困惑,你的意思是它会自动更新数据源吗?
  • @Nan 你是怎么得到数据表的?以编程方式还是来自数据库?在我的测试中,我以编程方式创建了一个数据表并填充了数据。然后它会自动更新。
  • 以编程方式。我一开始是一个 csv 文件,出于演示目的,我将数据导出到日期表中。你能把你的代码写在解决方案中,让我看看。谢谢。

标签: c# .net visual-studio datagridview datasource


【解决方案1】:

这是我的测试。

public Form1()
{
    InitializeComponent();
    testdgv.CellClick += testdgv_CellClick;
}

DataTable table = new DataTable();

private void Form1_Load(object sender, EventArgs e)
{
    table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Description", typeof(string));

    table.Rows.Add(1, "KKK", "Des1");
    table.Rows.Add(2, "YYY", "Des2");
    table.Rows.Add(3, "LLL", "Des3");
    table.Rows.Add(4, "EEE", "Des4");
    table.Rows.Add(5, "TTT", "Des5");

    testdgv.DataSource = table;
}

private void testdgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // if Description clicked, delete the row
    if (e.ColumnIndex == testdgv.Columns["Description"].Index)
    {
        System.Console.WriteLine("delete button pressed!");
        testdgv.Rows.RemoveAt(e.RowIndex);
    }
}

// test
private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < table.Rows.Count; i++)
    {
        string ID = table.Rows[i][0].ToString();
        Console.WriteLine(ID);
    }
}

测试结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    相关资源
    最近更新 更多