How to update SQL Server database using Datagridview binding source C#

前端 未结 2 1896
抹茶落季
抹茶落季 2021-01-13 15:42

I\'m writing a Winforms app in C# that enables the user to edit and update database using the datagridview.

The problem is, I can\'t make it to work. The only thing

相关标签:
2条回答
  • 2021-01-13 16:25

    Without calling bindingSource1.EndEdit your underlying DataTable doesn't see any change and thus the Update command has nothing to update.

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        bindingSource1.EndEdit();
        DataTable dt = (DataTable)bindingSource1.DataSource;
    
        // Just for test.... Try this with or without the EndEdit....
        DataTable changedTable = dt.GetChanges();
        Console.WriteLine(changedTable.Rows.Count);
    
        int rowsUpdated = da.Update(dt);    
        Console.WriteLine(rowsUpdated);
    }
    
    0 讨论(0)
  • 2021-01-13 16:25

    You can have a save or update button to execute the code like this:

    bindingSource1.EndEdit();
    DataTable dt = (DataTable)bindingSource1.DataSource;   
    dataAdaper.Update(dt);    
    

    You will save all changes you made, but if you sort datagridview columns first then change data then run the save code above you will miss one record, the top first one before you sort. To fix it, you have to sort it back then save them. The best way to do it if you know which column to sort, you need to sort it when you load data to datagridview.

    Jia Zhuang

    0 讨论(0)
提交回复
热议问题