0

Windows フォーム アプリケーションに DataGridView コントロールがあります。私がやりたいことはこれです:ビューをリロードして、バインドされているデータベーステーブルに変更が発生したときに正しいデータが表示されるようにします。つまり、DataGridView1.Rows.Remove(DataGridView1.CurrentRow) プロパティではなく SQL クエリを使用してレコードを削除すると、データグリッドビューにも変更が加えられます。例: datagridview にバインドされた顧客テーブルがあります。レコードを削除すると、たとえば ID=5 のレコードが実行時にグリッドビューから削除されます。これは可能ですか?

編集:

データソースを再バインドするために、顧客を削除するたびにこの手順を呼び出しています

Private Sub reloadDataset()
        DataGridView1.DataSource = ""
        DataGridView1.DataSource = CustomerBindingSource
    End Sub

それはうまくいきません....何が間違っていますか?がんばってくれてありがとう..

編集2

明確にするために: CustomerBindingSource には DataSource(myDatasource) と datamember テーブル customers があります

4

1 に答える 1

2

あなたが投稿した限られたコードからはわかりませんが、BindingSource を使用している場合は、DataGridView DataSource ではなく、DataSource をリロードしていることを確認する必要があります。DataGridView は、同じ BindingSource にバインドされたままにすることができます。

Private Sub Load()

   'Tell DataGridView to use BindingSource.
    DataGridView1.DataSource = CustomerBindingSource

   'Fetch the table.
   'Tell the BindingSource what you want it to wrap/use as it's DataSource.
   CustomerBindingSource.DataSource = FetchData()

End Sub

Private Sub Reload()

   'We have made some changes and need to refresh/reload.
   'We need to re-fetch the table and re-bind it to BindingSource's DataSource.
   CustomerBindingSource.DataSource = FetchData()

End Sub

Private Function FetchData() as DataTable

     Using Conn As New Data.SqlClient.SqlConnection("connectionString"),
        Command As New Data.SqlClient.SqlCommand("SQLQuery", Conn),
        Adapter As New Data.SqlClient.SqlDataAdapter(Command)

        Dim Table As New DataTable

        Adapter.Fill(Table)

        Return Table

    End Using

End Function

FetchData は、BindingSource がバインドできるデータ テーブルを返しますが、バインドできる任意のオブジェクトを返すことができます。この FetchData の実装は、SQL Server に固有のものであることに注意してください。

于 2012-06-01T19:32:54.023 に答える