我有一个填充数据网格的函数。
Public Sub GridMiner()
'check summary and database
Try
con.Open()
sql = "Select roomnumber AS [Room], [end] AS [Check out at], hours as [on] FROM rooms where [end] between ? and ?"
cmd = New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("@from", Now.AddDays(0).ToString("MM/dd/yyyy"))
cmd.Parameters.AddWithValue("@to", Now.AddDays(1).ToString("MM/dd/yyyy"))
da = New OleDb.OleDbDataAdapter(cmd)
da.Fill(ds)
gridSummary.DataSource = ds.Tables(0)
da = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
它填充名为gridSummary
的数据网格现在当我从不同的表单中将一些数据保存到我的数据库表时,我的数据网格不会刷新它的值,我决定创建一个刷新按钮。
Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
GridMiner()
End Sub
不是刷新我的数据网格上的数据,而是添加相同的内容及其新数据。
答案 0 :(得分:0)
您需要定义主键才能正确合并表。
“如果存在主键信息,则任何重复的行都会被协调,并且只在与DataSet对应的DataTable中出现一次。主键信息可以通过FillSchema设置,通过指定DataTable的PrimaryKey属性,或者将MissingSchemaAction属性设置为AddWithKey。“ - MSDN
因此,在 FillSchema
之前调用da.Fill(ds)
将确保数据集具有核心架构。
da.FillSchema(ds, SchemaType.Source)
答案 1 :(得分:0)
好的,感谢@LordTakker和评论的所有人
我通过新的数据集找到了答案,它就是诀窍。见代码:
Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
Try
con.Open()
sql = "Select roomnumber AS [Room], [end] AS [Check out at], hours as [on] FROM rooms where [end] between ? and ?"
cmd = New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("@from", Now.AddDays(0).ToString("MM/dd/yyyy"))
cmd.Parameters.AddWithValue("@to", Now.AddDays(1).ToString("MM/dd/yyyy"))
da = New OleDb.OleDbDataAdapter(cmd)
da.Fill(ds)
gridSummary.DataSource = ds.Tables(0)
datatb = New DataTable()
datatb.Load(cmd.ExecuteReader())
gridSummary.DataSource = datatb
da = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
现在这个工作。谁能告诉我这是不是最好的做法。
根据Bjørn-Roger Kringsjå
使用此解决方案,您将遇到桌面的两个实例。 datatb和ds.Tables(0)。此外,您正在加载表两次,da.Fill(ds)和datatb.Load(cmd.ExecuteReader())。并且,通过更改网格的数据源,您将失去用户所做的所有选择。
所以我已将上面的代码编辑为:
Public Sub btnRefresh_Click(sender As Object, e As EventArgs)
Try
con.Open()
sql = "Select roomnumber AS [Room], [end] AS [Check out at], hours as [on] FROM rooms where [end] between ? and ?"
cmd = New OleDb.OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("@from", Now.AddDays(0).ToString("MM/dd/yyyy"))
cmd.Parameters.AddWithValue("@to", Now.AddDays(1).ToString("MM/dd/yyyy"))
datatb = New DataTable()
datatb.Load(cmd.ExecuteReader())
gridSummary.DataSource = datatb
da = Nothing
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub