【问题标题】:Reload the DataGridView when changes occur to its dataset vb.net当数据集 vb.net 发生更改时重新加载 DataGridView
【发布时间】:2012-06-01 08:43:10
【问题描述】:

我的 Windows 窗体应用程序中有一个 DataGridView 控件。我想做的是: 我想重新加载视图,以便在绑定的数据库表发生更改时显示正确的数据。 换句话说,当我使用 sql 查询而不是 DataGridView1.Rows.Remove(DataGridView1.CurrentRow) 属性删除记录时,我希望对 datagridview 也发生更改。 例如:我有一个绑定到 datagridview 的客户表。当我删除一条记录时,比如说 ID=5 的记录,我希望在运行时从 gridview 中删除该行。这可能吗?

编辑:

我每次删除客户时都会调用此过程以重新绑定数据源

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

但它不起作用....我做错了什么? 谢谢你的努力。。

编辑 2

澄清一下:CustomerBindingSource 有 DataSource(myDatasource) 和数据成员表 customers

【问题讨论】:

  • 为了反映您需要在进行更改时将集合绑定回网格的更改。请显示您尝试过的代码

标签: sql-server vb.net visual-studio-2010


【解决方案1】:

我无法从您发布的有限代码中看出,但如果您使用的是 BindingSource,则需要确保重新加载它是 DataSource,而不是 DataGridView 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。

【讨论】:

  • 感谢凯西威尔金斯的回复。因此,如果我做对了,您建议我创建一个 DataTable,它将填充数据库中的数据。 sub load() 将是我的 form_load()。然后我对数据库中的表进行更改(删除、添加客户),然后通过调用 sub Reload() 将 DataTable 重新绑定为 NewTableData?
  • 本质上是的。关键是确保您 a) 使用更改的数据重新加载 DataTable,b) 将新的 DataTable 重新绑定到 BindingSource。我很快会用更多代码来更新我的答案。
  • 非常感谢凯西。我使用的逻辑与 urs 相同,只是我使用 DataReader 进行数据获取!再次感谢您的帮助
猜你喜欢
  • 2022-08-14
  • 1970-01-01
  • 2012-04-25
  • 2012-02-12
  • 2014-08-09
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多