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!
You can supply an array of
object
to theAdd
method of theDataGridView
:I'm assuming
myTempDG
is aDataGridView
, in that case you can cast the rows of themyTempDG
to an array ofDataGridViewRow
and thenAddRange
: