2012-01-30 39 views
0

我越來越混淆有關數據集和數據視圖,這是我無論是使用數據集來更新數據或數據視圖過濾數據,但在同一時間不能兼得在一起。關於datagridview的更新數據和過濾

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 

,所以我希望一些1可以告訴我,怎麼我可以在同一時間有兩個功能「更新過濾器」使用什麼數據源?

回答

0

您必須使用數據集(或數據表)與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。