I have a DataGridView of 3 columns and 3 rows (it’s just an example). I would like to read only the value of a specific cell (in this example 2×2). How do you do this? I try this code but visual studio write me there is an error:
"An unhandled exception of type ‘System.ArgumentOutOfRangeException’ occurred in mscorlib.dll
Additional information:
Index non compreso nell’intervallo. Richiesto valore non negativo e minore della dimensione della raccolta."
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'read array and send to DataGridView
Dim cella(3, 3) As String
cella(0, 0) = "Papa"
cella(0, 1) = "Mamma"
cella(0, 2) = "Bimbo1"
cella(0, 3) = "Bimbo2"
cella(1, 0) = "Bianco"
cella(1, 1) = "Rosso"
cella(1, 2) = "Nero"
cella(1, 3) = "Blu"
cella(2, 0) = "Firenze"
cella(2, 1) = "Pisa"
cella(2, 2) = "Livorno"
cella(2, 3) = "Empoli"
cella(3, 0) = "Gatto"
cella(3, 1) = "Cane"
cella(3, 2) = "Panda"
cella(3, 3) = "Macaco"
For x As Integer = 0 To 3
DataGridView1.Columns.Add("newColumnName", "Testo")
Next
For y As Integer = 0 To cella.GetUpperBound(0)
DataGridView1.Rows.Add(cella(0, y), cella(1, y), cella(2, y), cella(3, y))
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Create MsgBox with the value of the specified cell
MsgBox(DataGridView1.SelectedRows.Item(2).Cells(2).Value.ToString())
End Sub
2
Answers
Don’t store the data in the UI. UI is for display and interaction, not for storing state.
Create a class to represent your data
then populate the list with instances of the class and bind the data to the DataGridView
and finally find the item you are looking for using some logic
Now your data is off the UI, and you can access it using logical names, pass the data around, query it, etc.
The Exception occur because you have no SelectedRows. If you want only a fix cell try
Row
insteed ofSelectedRows
: