在C#中更新数据网格视图后如何更新数据源

How to update the data source after updating the data grid view in c#

我现在正在我的数据网格视图中添加删除功能。 我通过代码添加了删除按钮,打算通过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!,表示Event触发成功。 但是,我 运行 遇到了问题;删除特定行的单元格后如何更新下划线数据源? 数据源代码为:

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

这是我的测试。

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);
    }
}

测试结果: