使用dataview更新DataGridView

时间:2012-07-25 04:25:01

标签: database datagridview filter dataview

我有一个VB.NET 2010应用程序,可以将数据从SQL Server加载到datagridviewadapter.fill()。当我更新数据库时它工作正常但我的问题是,当我使用数据视图根据组合框选择过滤数据时,方法adapter.update(table)不起作用!

是否可以使用过滤器进行操作?

Private Sub cmbDepartment_SelectedIndexChanged(...) 
        Handles cmbDepartment.SelectedIndexChanged 
    Dim filter As String 
    Try 
        lblDepartmentId.Text =   ds.Tables("department").Rows(cmbDepartment.SelectedIndex)(0) 
        filter = "dprtId = " & lblDepartmentId.Text 
        dvSection = New DataView(ds.Tables("section"), filter, "", DataViewRowState.CurrentRows) 
        table = dvSection.ToTable 
        dgvSections.DataSource = table 
    Catch ex As Exception 
        MsgBox(Err.Description) 
    End Try 
 End Sub

Private Sub btnSaveDepartment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 
        Handles btnSaveDepartment.Click 
    Dim cbDep As SqlCommandBuilder 
    Dim numRows As Integer 
    Try cbDep = New SqlCommandBuilder(daDep) 
        Me.Validate() numRows = daDep.Update(ds.Tables("section")) 
        MsgBox(numRows & " Rows affected.") 
    Catch ex As Exception 
        MsgBox(Err.Description) 
    End Try 
End Sub

1 个答案:

答案 0 :(得分:0)

您目前正在进行过滤的方法是创建一个新的DataTable并将其绑定到DataGridView数据源。这会破坏原始DataSet与该表之间的关联,因此当您调用Update时,您的更改将无法恢复。

尝试更改为类似下面的代码(我省略了try catch块,它们不会改变修复问题的想法)。

首次将数据源设置为网格时,将其设置为表单级别的私有dvSection字段:

Public Class Form1

    ' Here we declare some class level variables. 
    'These are visible to all members of the class

    Dim dvSection As DataView
    Dim tableAdapter As New DataSet1TableAdapters.CustomersTableAdapter()
    Dim ds As New DataSet1()


    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

       ' We fill our dataset - in this case using a table adapter
        tableAdapter.Fill(ds.Customers)
        dvSection = ds.Customers.DefaultView

        DataGridView1.DataSource = dvSection

    End Sub

    ' Here is the code to filter.
    ' Note how I refer to the class level variable dvSection
    Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

        Dim filter As String 

        lblDepartmentId.Text =   ds.Tables("department").Rows(cmbDepartment.SelectedIndex)(0) 

        filter = "dprtId = " & lblDepartmentId.Text 
        dvSection.RowFilter = filter 

        dvSection.RowFilter = filter

    End Sub

    ' And here is the update code referring to the class level table adapter
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        tableAdapter.Update(ds.Customers)
    End Sub
End Class

另一种可能使事情变得更容易的方法是引入绑定源并在其上设置过滤器。但要么是应该正常工作。