如何在添加行之前使用Datagridview.rows.add()合并该行的数据



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

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(这是我的数据源btw)的7列。但是,如果我又添加了两列(这使它成为9列),该怎么办。然后我必须编辑源代码(添加"srow.cells(7).value.tostring,srow.cell(8).value…etc")

我知道如何在列中循环,但不知道如何将其转换为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))。

提前感谢你们,祝你们今天愉快!

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

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)

好的,我得到了

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

最新更新