【问题标题】:Clearing DataGridView bound to DataSet without losing headers VB.NET清除绑定到 DataSet 的 DataGridView 而不会丢失标头 VB.NET
【发布时间】:2016-11-01 09:29:14
【问题描述】:

我目前有一个应用程序,您可以搜索特定位置、所有者等,它会返回有关设备的一些基本信息。我通过 SQL 查询提取了这些信息,并将其放入 DataSet 中,然后将其放入 DataGridView 对象中。我正在尝试实现一个清除按钮,它将删除搜索词以及 DataGridView 对象中的数据。

不幸的是,我无法使用DataGridView.Rows.Clear(),因为我的 DataGridView 已绑定到 DataSet。我在使用DataGridView.DataSource = Nothing 时遇到了困难,因为这不仅会删除显示的数据,还会删除我为 DataGridView 创建的列的标题。我已经尝试了一些我发现的解决方案,例如 DataGridView.Refresh()DataGridView.AutoGenerateColumns = false,但到目前为止这些已经删除了列标题。

这是我用来向 DataGridView 对象添加行的代码;

    Dim con As New SqlClient.SqlConnection(getConnectionString)
        Dim cmd As New SqlCommand("SELECT asset.assetID, owner.ownerName, model.brand, asset.modelID, deviceOwner.serialNumber, deviceOwner.location, asset.dateAssessed from asset 
                                  join deviceOwner on asset.assetID = deviceOwner.assetID
                                  join owner on deviceOwner.ownerID = owner.OwnerID
                                  join model on asset.modelID = model.modelID where asset.dateAssessed = @checkDate", con)
        cmd.Parameters.AddWithValue("@checkDate", searchEnterDate.Text.ToString)
        con.Open()
        Dim myDA As New SqlDataAdapter(cmd)
        myDA.Fill(myDataSet, "MyTable")
        displayResults.DataSource = myDataSet.Tables("MyTable").DefaultView
        con.Close()
        con = Nothing

我正在寻找一种解决方案,该解决方案允许我在不删除列标题的情况下清除 DataGridView 中的行,以便我可以在必要时使用清除按钮,但在仍显示列标题的情况下继续搜索。

【问题讨论】:

  • 如何创建一个仅包含列标题的数据表,并在您想“空白”时将其分配为您的数据源?
  • 如果 col 标题相同,则意味着查询可能基本相同,只是被过滤了。您可以尝试使用DefaultView.RowFilter,而不是运行新查询。
  • 我使用从 DataTable 派生的 DataView 并根据需要设置过滤器。

标签: vb.net datagridview dataset


【解决方案1】:

您可以Clone DataTable 保留列但“删除”数据:

Dim oldTable As DataTable = CType(displayResults.DataSource, DataView).Table
Dim emptyTable As DataTable = oldTable.Clone()
displayResults.DataSource = emptyTable ' or emptyTable.DefaultView

或在旧表上使用DataRowCollection.Clear,这可能会导致更多副作用:

oldTable.Rows.Clear() 

【讨论】:

  • 克隆是我的想法。好主意。
  • 这完全符合我的需求。谢谢您的帮助!如果 dataTable 已经为空,它会给我一些错误,但我可以为此进行错误处理!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 2011-01-14
  • 2014-02-07
  • 1970-01-01
  • 2012-07-01
  • 2014-01-31
相关资源
最近更新 更多