How to consolidate data for a row before adding it using Datagridview.rows.add()?

592 views Asked by At

I bumped into this problem because I would like my code to work even though I have added new columns to the source. My code adds a row based on the number of rows of the source. My code lacks the ability to consider the number of columns. Here is my code:

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

The code above works okay given that I have 7 columns from tempDG (which is my datasource btw). But what if I have added two more columns (which makes it 9). I would then have to edit the code from the source (add "srow.cells(7).value.tostring, srow.cells(8).value... etc")

I know how to loop through the column but I do not know how to convert it to a data that can be read by rows.add function. This is what I've tried so far:

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

How can I create a collection of data first before adding it using the rows.add() function? Also may I know what kind of data is needed by rows.add()? I am assuming it is a list of values (in my case, I used List(of String)).

Thank you guys in advance and have a nice day!

2

There are 2 answers

1
Tea With Cookies On

You can supply an array of object to the Add method of the DataGridView:

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

I'm assuming myTempDG is a DataGridView, in that case you can cast the rows of the myTempDG to an array of DataGridViewRow and then AddRange:

Dim rows() As DataGridViewRow
rows = myTempDG.Rows.Cast(Of DataGridViewRow)().ToArray
dataGridView1.Rows.AddRange(rows)
1
E-r Gabriel Doronila On

OK I GOT IT

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

But it seems a little slow..

This is much better.. after considering to not transfer the dataset to tempDG..

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