简体   繁体   中英

How to Insert and Update datagrid row in database table

I am developing C# without using any framework.until now i successfully performed following task on Datagrid.

1.Displaying data in Data-grid by binding with database table
2.Getting the selected row data from Data-grid based on primary key

Here is my variable declaration :

SQLiteDataAdapter adap;
SQLiteCommandBuilder cmdbl;
DataSet ds;
String Query;
DataTable dt;

Here is code for displaying data in Data-grid :

try
{
    Query = "Select * from Items";
    adap = new SQLiteDataAdapter(Query, GlobalVars.conn);
    ds = new DataSet();
    adap.Fill(ds, "Items");
    dt = ds.Tables[0];
    dtgitems.DataContext = ds.Tables[0].DefaultView;
    dtgitems.ItemsSource = dt.DefaultView;
    ds.Dispose();
    adap.Dispose();
    dt.Dispose();
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

It is working fine and here is my code for updating that data-grid

try
 {
     cmdbl = new SQLiteCommandBuilder(adap);
     adap.Update(ds, "Items");
    // ds.Tables[0].Clear();
 }
 catch (Exception ex)
 {

 }

it is not working .Does anyone knows how i can accomplish this update functionality in data-grid ? .Please help me to correct this code for update opreation .Thanks

Although I would work with an ObservableCollection, you can update your datagrid items with the following code:

dtgItems.Items.Refresh();

Do this after you updated the source. I should use it in your code like this: You should accept the changes so your database gets updated.

try
{
    cmdbl = new SQLiteCommandBuilder(adap);
    adap.Update(ds, "Items");
    ds.Tables[0].AcceptChanges();
    dtgItems.Items.Refresh();
}
catch (Exception ex)
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM