0

datagridviewSQLServerからを介してデータをロードするVB.NET2010アプリケーションがあります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データソースにバインドすることです。これにより、元のデータセットとそのテーブルの間の関連付けが解除されるため、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

物事を簡単にする可能性のあるもう1つのアプローチは、バインディングソースを導入し、それにフィルターを設定することです。ただし、どちらも正常に機能するはずです。

于 2012-07-29T09:50:47.360 に答える