DataGridView cell substring

ReDig212

New member
Joined
Jan 7, 2013
Messages
2
Programming Experience
1-3
Hi Guys,

I have some code:

VB.NET:
 Dim s1 As String
   For Each row As DataGridViewRow In DataGridView1.Rows
                For i As Integer = 0 To row.Cells.Count - 1
                    s1 = row.Cells(i).Value.substring(9, 10)
               //do something with s1
                   s1 = Nothing
                Next i
            Next row

I want to loop over each cell in column 0 and get the substring of it; then assign to to string variable "s1", only I can't figure out how to target column 0. I know it's probably really simple, but I can't see it at the minute.

Any help would be greatly received.

Thanks
 
If you are only interested in the first column (index 0) then you don't need the inside loop. The outer loop will go over each row and you can directly set

s1 = row.Cells(0).Value.Substring(9, 10)
 
Thanks for the quick reply.

I had tried similar approaches, by using that one I get the following error:

Object variable or With block variable not set.

Code at present:

VB.NET:
            For Each row As DataGridViewRow In DataGridView1.Rows
                s1 = row.Cells(0).Value.Substring(9, 10)

//do something with s1

Next row

I'm not sure where I'm going wrong, but I've tried a few different methods and I'm slowly going mad!

Thanks
 
The error is caused because the last row is not actually populated (it is the row for new data). You should be able to modify your code with a simple check on the row, as follows:

Dim s1 As String

For Each row As DataGridViewRow In Me.DataGridView1.Rows
     If Not row.IsNewRow Then
          s1 = row.Cells(0).Value.Substring(9, 10)
     End If
Next row
 
Back
Top