数据网格视图更新,在vb.net窗体中编辑和删除表单,即使用多个表来填充datagridview

时间:2014-01-06 07:20:14

标签: vb.net winforms datagridview

我是Windows窗体应用程序的新手......

我正在使用VB.NET windows窗体并处理DataGridView ...

我已经从两个表中填充了DataGridView

请告诉我如何添加,删除和编辑/更新DATAGridview的记录回数据库。

我正在使用SQLSERVER 2008 DataBase

我有两个表1->CompanyMaster_tbl,其中有两个字段。 Cid and CompanyName

  

Cid是此表的主键

2-> DepartmentMaster_tbl这个有4个字段。 dtid,dtname,dtphon,dtmail,Cid

  

dtid是主键,Cid是外键。   我的数据网格视图如下所示:enter image description here

Dim adapter As SqlDataAdapter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

  'NOTE: I removed the Using statements to ease your tests/understanding, but you shouldn't let the connections opened (or, at least, set connection-release part somewhere)
  Dim con As SqlConnection = New SqlConnection() 'SET THE CONNECTION STRING
  con.Open()

  adapter = New SqlDataAdapter("select c.CompanyName,d.dtName,d.dtPhone,d.dtEmail  from CompanyMaster_tbl c join  DepartmentMaster_tbl d on c.Cid=d.cId", con)

  Dim dt As DataTable = New DataTable()
  adapter.Fill(dt) 'Filling dt with the information from the DB
  gv.DataSource = dt 'Populating gv with the values in dt

End Sub

在更新按钮中,我写了这样的代码:

Dim dt1 As DataTable = DirectCast(gv.DataSource, DataTable)
adapter.Update(dt1)

但在gridview中编辑任何内容之后,我点击了更新按钮,但我在这一行中收到错误

  

da.Update(DT1)

错误: 当传递带有修改行的DataRow集合时,更新需要有效的UpdateCommand。

提前致谢

1 个答案:

答案 0 :(得分:0)

如果要在DataGridView和数据库之间保持一些同步,则不应手动添加列/行,而应依赖DataSource属性。适合您案例的示例代码:

Using con As SqlConnection = New SqlConnection() 'You have to set the CONNECTION STRING
    con.Open()

    Using adapter As SqlDataAdapter = New SqlDataAdapter("select c.CompanyName,d.dtName,d.dtPhone,d.dtEmail  from CompanyMaster_tbl c join  DepartmentMaster_tbl d on c.Cid=d.cId", con)

        Dim dt As DataTable = New DataTable()
        adapter.Fill(dt) 'Filling dt with the information from the DB
        gv.DataSource = dt 'Populating gv with the values in dt

    End Using
End Using

上面的代码会从数据库中提取您想要的所有信息,将其放入DataTabledt),然后将其作为DataGridView提供给DataSourcegv现在拥有dt的所有值; dt中的任何更改都会反映在gv中,反之亦然(这种耦合几乎是完美的,至少在更新值时;删除行/列或更改其基本配置时可能会出现一些问题) 。您甚至可以将adapter保留为全局变量(在Using语句之外)并依赖它来定期更新数据库(例如,通过adapter.Update(dt))。

有很多选择;但是,无论如何,在你的条件下依赖DataSource肯定会更好。