使用sqlite,wpf和C#在链接的db表中插入和更新数据网格行

时间:2013-10-13 16:23:39

标签: c# sqlite datagrid wpf-controls

我将用于链接db table和datagrid的sqlite代码是:

 sqlitecon.Open();
 string Query2 = "Select * from Security_details "; 
 SQLiteCommand createCommand2 = new SQLiteCommand(Query2, sqlitecon);  createCommand2.ExecuteNonQuery();
 SQLiteDataAdapter dataAdp2 = new SQLiteDataAdapter(createCommand2);
 DataTable dt2 = new DataTable("Security_details");
 dataAdp.Fill(dt2);
 datagrid_security.ItemsSource = dt2.DefaultView;
 dataAdp2.Update(dt2); 
 sqlitecon.Close();

此代码在表单加载事件期间将db表链接到datagrid。

我希望用户能够:

  • 在datagrid上添加新行get插入db
  • 编辑datagrid上的现有行,将其更新为db。

以下查询是我的数据库字段

SQLiteCommand comm = new SQLiteCommand("update Security_details  " + 
      "set id=@id,Code=@Code,Description=@Description,Rate=@Rate," + 
      "Qty=@Qty,Amount=@Amount,Remarks=@Remarks where id=@id", sqlitecon);

请告诉我通过datagrid插入和编辑db表的命令集?谢谢

1 个答案:

答案 0 :(得分:2)

SQLiteDataAdapter的声明移动到全局类级别,并在那里声明SQLiteCommandBuilder。然后,在将数据绑定到网格之前,初始化SQLiteCommandBuilder,它将自动创建适合您的表的UPDATE / INSERT / DELETE命令(假设SELECT返回表的主键)

此时,当您准备好将数据提交到数据库时,请调用全局SQLiteDataAdapter实例的Update方法

public class YourClass
{
     SQLiteDataAdapter dataAdp2;
     SQLiteCommandBuilder cmdBuilder;
     .....


     public void BindMyGrid()
     {
          sqlitecon.Open();
          string Query2 = "Select * from Security_details "; 
          SQLiteCommand createCommand2 = new SQLiteCommand(Query2, sqlitecon);                

          dataAdp2 = new SQLiteDataAdapter(createCommand2);
          cmdBuilder = new SQLiteCommandBuilder(dataAdp2);
          DataTable dt2 = new DataTable("Security_details");
          dataAdp2.Fill(dt2);
          datagrid_security.ItemsSource = dt2.DefaultView;
          sqlitecon.Close();
     }
     ....
     public void SubmitData()
     {
          dataAdp2.Update((datagrid_security.ItemsSource As DataView).Table);
     }
     ......
}

如果你需要更深入地讨论这个过程you could read this MSDN article,它是相当陈旧的,关于SQL Server,它是在VB.NET中,但基本概念是相同的。