Luk*_*uke 0 vb.net datagridview sqldataadapter
简单的问题:
当我在SqlDataAdapter.Fill(DataGridView.DataSource)最初创建第一个数据后第二次调用时,它不会更新包含的行。它只是将 select 命令返回的所有行添加到我的 DataGridView 中。
如果我将其称为第三个、第四个(依此类推),它也只会添加返回的行。
我对 .Fill(DataTable) 函数的理解是否错误?如何正确更新已经存在的DataTable?哪一行代码负责?
事实证明,这一定是代码问题;
DataGridView1.AutoGenerateColumns = False
Dim sql = "select * from myTable"
oDtSource = New DataTable
oAdapter = New SqlDataAdapter
oCon = sqlCon("serverName\Instance", "myDataBase") ' Returns a SqlConnection
oCmd = New SqlCommand(sql, oCon)
oCon.Open()
oDtSource.Clear()
oAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oDtSource)
DataGridView1.DataSource = oDtSource
Run Code Online (Sandbox Code Playgroud)
为了刷新我使用oAdapter.Fill(oDtSource)
PrimaryKey 在数据库中设置
来自MSDN:
您可以
Fill在同一个DataTable. 如果存在主键,传入的行将与已存在的匹配行合并。如果不存在主键,传入的行将附加到 DataTable 中。
So either define a primary key or clear the table first.
Dim table = CType(DataGridView.DataSource, DataTable)
table.Clear()
' fill ...
Run Code Online (Sandbox Code Playgroud)
To define primary key(s) manually read this. To let it create automatically if they are defined in the database you need to set the MissingSchemaAction to AddWithKey:
' ...
dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
' fill ...
Run Code Online (Sandbox Code Playgroud)