【问题标题】:how to copy a DataGridView's content inside another如何将 DataGridView 内容复制到另一个内部
【发布时间】:2013-07-18 22:55:58
【问题描述】:

我有一个DataGridView,说dgA。这包含一些我需要在另一个DataGridView 中复制的信息,说dgB,只要单击按钮btn

如何在 Visual Basic 中做到这一点?

【问题讨论】:

  • 两个数据网格视图中的列是否相同? DataGridView 是否绑定到数据源?
  • 是的,完全一样。 DataGrid 绑定到一个 DataSource,但它是另一个子例程的内部,我不会让它成为全局的。

标签: vb.net datagridview


【解决方案1】:

您可以复制dgA的数据源(例如Being a DataTable),并将dgB绑定到它。您应该在 2 个网格上获得相同的数据源。

例子:

Dim dtSource As New DataTable
' Configure your source here...

' Bind first grid
    dgA.DataSource = dtSource
    dgA.DataBind()

' Use same data source for this grid...
    dgB.DataSource = dgA.DataSource
    dgB.DataBind()

然后,您可以从 .ASPX 更改网格显示方式的配置。您还可以使用会话,在不同的页面中使用。

【讨论】:

  • DataSource 是另一个子程序的内部,我不会让它成为全局的。
  • 也许将它存储在会话中?即你得到一个数据源,将它存储在一个会话中,这个会话将用于另一个网格?显然假设 dgA 先加载。
【解决方案2】:

非数据绑定 DataGridView

为什么不检查DataGridView1 (dgA) 的每一行并将单元格值发送到DataGridView2 (dgB)?

我在我的 DataGridViews 中添加了两列,因此将此代码分别应用于您的 datagridview 列。

Private Sub CopyDgv1ToDgv2_Click(sender As System.Object, e As System.EventArgs) Handles CopyDgv1ToDgv2.Click
    For Each r As DataGridViewRow In dgA.Rows
        If r.IsNewRow Then Continue For

        'r.Cells(0).Value is the current row's first column, r.Cells(1).Value is the second column
        dgB.Rows.Add({r.Cells(0).Value, r.Cells(1).Value})
    Next
End Sub

这会遍历我的第一个 DataGridView 的每一行,并在我的第二个 DataGridView 中添加一行,其中包含第一个 DataGridView 中包含的值。


DataBoundDataGridView

如果数据同时绑定在DataGridViews 上,那么您只需将数据源复制到另一个 DataGridView,如下所示:

Private Sub CopyDgv1ToDgv2_Click(sender As System.Object, e As System.EventArgs) Handles CopyDgv1ToDgv2.Click
    dgB.DataSource = dgA.DataSource
End Sub

【讨论】:

  • 我明白了...我以为只有第一个 DataGridView 绑定到数据源。在这种情况下,两者都必须绑定。
猜你喜欢
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多