Search code examples
c#.netvisual-studiodatagridviewdatasource

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


I am adding a delete function in my data grid view at the moment. I add the delete button by code, and I plan to trigger the delete function via 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);

            
        }
    }

I have been tested the function, the debug console actually prints out the delete button pressed!, which means the Event is triggered successfully. However, I am running into an issue; how to update the underline data source after I removed the cell at specific row? The data source code is :

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

Solution

  • Here is my test.

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

    Test result:

    enter image description here