【问题标题】:How to consolidate data for a row before adding it using Datagridview.rows.add()?如何在使用 Datagridview.rows.add() 添加行之前合并数据?
【发布时间】:2014-11-12 11:37:47
【问题描述】:

我遇到了这个问题,因为我希望我的代码能够工作,即使我已经向源代码添加了新列。我的代码根据源的行数添加一行。我的代码缺乏考虑列数的能力。这是我的代码:

For Each srow As datagridviewrow In mytempDG.Rows
   dataGridView1.Rows.Add(srow.Cells(0).Value.tostring, srow.Cells(1).Value.tostring, _
   & srow.Cells(2).Value.tostring, srow.Cells(3).Value.tostring,srow.Cells(4).Value.tostring, _
   & srow.Cells(5).Value.tostring, srow.Cells(6).Value.tostring)
Next

鉴于我有来自 tempDG 的 7 列(顺便说一句,这是我的数据源),上面的代码可以正常工作。但是,如果我又添加了两列(这使它成为 9)怎么办。然后我必须从源代码编辑代码(添加“srow.cells(7).value.tostring, srow.cells(8).value...等”)

我知道如何遍历列,但我不知道如何将其转换为可以由 rows.add 函数读取的数据。这是我迄今为止尝试过的:

Dim finrow As List(Of String)
finrow = New List(Of String)

For Each srow As datagridviewrow In mytempDG.Rows
   finrow.clear
   For Each scol As DataGridViewColumn In mytempDG.Columns
      finrow.add(srow.Cells(scol.Index).Value.ToString)             
   Next
   dataGridView1.Rows.Add(finrow)
Next

如何在使用 rows.add() 函数添加数据之前先创建数据集合?我也可以知道 rows.add() 需要什么样的数据?我假设它是一个值列表(在我的例子中,我使用 List(of String))。

提前谢谢你们,祝你有美好的一天!

【问题讨论】:

    标签: vb.net datagridview sharpdevelop


    【解决方案1】:

    您可以将object 的数组提供给DataGridViewAdd 方法:

    For Each srow As DataGridViewRow In mytempDG.Rows
       Dim obj(mytempDG.Columns.Count) as Object
       For col as Integer = 0 to mytempDG.Columns.Count - 1
           obj(col) = srow.Cells(col).Value.ToString()
       Next
       dataGridView1.Rows.Add(obj)
    Next
    

    我假设myTempDGDataGridView,在这种情况下,您可以将myTempDG 的行转换为DataGridViewRow 的数组,然后再转换为AddRange

    Dim rows() As DataGridViewRow
    rows = myTempDG.Rows.Cast(Of DataGridViewRow)().ToArray
    dataGridView1.Rows.AddRange(rows)
    

    【讨论】:

    • 'Cast' 不是 'System.Windows.Forms.DatagridviewRowCollection' 的成员。我也尝试过从数据行进行强制转换。根据错误,cast 也不是成员
    【解决方案2】:

    好的,我知道了

    Dim numcol As Integer = mytempDG.Columns.count
    Dim finrow(numcol) As String
    
    For Each srow As datagridviewrow In mytempDG.Rows
       For Each scol As DataGridViewColumn In mytempDG.Columns
          finrow(scol.Index) = srow.Cells(scol.Index).Value.ToString            
       Next
       dataGridView1.Rows.Add(finrow)
    Next
    

    不过好像有点慢..

    这好多了..在考虑不将数据集传输到 tempDG 之后..

    For each xrow as DataRow in ds.Tables(0).Rows
       datagridview1.Rows.Add(xrow.ItemArray)
    Next
    

    【讨论】:

    • 你试过设置datagridview1Datasource吗? datagridview1.DataSource = ds 这会将数据集行复制到 dgv 中。
    猜你喜欢
    • 2018-08-28
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多