Link to home
Start Free TrialLog in
Avatar of PNRT
PNRT

asked on

vb.net get datagridview column into an array

Hi Experts.  I have a datagridview where the first column is a list of numbers and need to get the column into an array (not an array list).

I'm trying

         Dim list() As Integer
         For RowIndex As Integer = 0 To DataGridView1.Rows.Count - 1 Step 1
            list(RowIndex) = DataGridView1(0, RowIndex).Value
        Next RowIndex

Open in new window



But keep getting the error   Object reference not set to an instance of an object.

I've tried many different methods but keep getting the same error

Any help would be appreciated
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

add Imports System.Linq
and use this code:

Dim arr As Integer() = DataGridView1.Rows.Cast(Of DataGridRow)().Select(Function(n) Int.Parse(n(0).Value)).ToArray()

Open in new window

Avatar of PNRT
PNRT

ASKER

Thanks But got errors
First was
Type 'DataGridRow' is not defined
Changed to DataGridViewRow
Then got
Overload resolution failed because no accessible 'Select' can be called with these arguments:      

Is it not possible without Linq?
try replace line 3 with:
list(RowIndex) = DataGridView1.Rows(RowIndex)(0).Value

Open in new window

Avatar of PNRT

ASKER

Thanks
But With
list(RowIndex) = DataGridView1.Rows(RowIndex)(0).Value
I get the error
Class 'System.Windows.Forms.DataGridViewRow' cannot be indexed because it has no default property

Sorry, no idea what its referring to
  Dim list As List(Of Integer) = New List(Of Integer)

        For Each d In DataGridView1.Rows.Cast(Of DataGridViewRow)()
            Dim num As Integer
            If Int32.TryParse(d.Cells(0).Value, num) Then
                list.Add(num)
            End If
        Next

Open in new window

Avatar of PNRT

ASKER

Sorry, I mentioned in the first question above it had to be a simple array not a list as I need to send the array to a function that requires an array.

I didn't realize it would be so difficult just to get a column of numbers into an array.
ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial