我对数据集和数据视图感到困惑,我使用数据集来更新数据或使用数据视图来过滤数据,但不能同时将两者放在一起。
Private Sub searchStaff_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ds = New DataSet
dv = New DataView
Dim ad As New SqlDataAdapter("SELECT * FROM staff", connection)
ad.Fill(ds, "staff")
dv.Table = ds.Tables("staff")
Me.DataGridView1.DataSource = dv
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Try
dv.RowFilter = "StaffName like '" & txtSearch.Text & "*'"
Catch ex As Exception
End Try
End Sub
这是在dataview上过滤数据的代码,对我来说很好。 但是后来,我必须在datagridview上实现更新数据的另一个功能,我在互联网上找到的东西要求我使用数据集作为数据源而不是数据视图。
Private Sub searchStaff_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connection = New SqlConnection(connectionString)
ds = New DataSet
cmd = New SqlCommand("SELECT * FROM staff", connection)
adp=New SqlDataAdapter(cmd)
adp.Fill(ds, "staff")
Me.DataGridView1.DataSource = ds
Me.DataGridView1.DataMember = "staff"
End Sub
Private Sub btnUpdate_ClickEvent(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.ClickEvent
Dim cmdbuilder As New SqlCommandBuilder(adp)
Dim i As Integer
Try
i = adp.Update(ds, "staff")
MsgBox("Record updated= " & i)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
所以我希望有些人可以告诉我,如何通过使用什么数据源同时让两个函数“更新,过滤”?
答案 0 :(得分:0)
您必须将DataSet(或DataTable)与SqlDataAdapter一起使用才能进行更新操作; DataView用于过滤数据,但不提交对数据库的更改。这是searchStaff_Load方法的一个示例:
Private Sub searchStaff_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connection = New SqlConnection(connectionString)
ds = New DataSet
cmd = New SqlCommand("SELECT * FROM staff", connection)
adp=New SqlDataAdapter(cmd)
adp.Fill(ds, "staff")
Me.DataGridView1.DataSource = ds.Tables("staff").DefaultView 'Assign DataView to grid
'Me.DataGridView1.DataMember = "staff" 'No need when using DataView
End Sub
txtSearch_TextChanged和btnUpdate_ClickEvent已经正确无误。第一个过滤器使用DataView,第二个更新数据库使用DataSet。