0

我有一个 VB.NET 2010 应用程序,它将数据从 SQL Server 加载到一个datagridview通过adapter.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
4

1 回答 1

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

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

于 2012-07-29T09:50:47.360 回答