drx_072 drx_072 - 1 year ago 240
Vb.net Question

Datagridview SelectedRows index error | Access and VB.NET

I have an error in my software. My form contains a DataGridView connected with MS_access database.

When I click on a row in the DataGridView, I get this error:

Index was out of range. Must be non-negative and less than the size of the collection.

Parameter name: index

My code:

If (DataGridView1.Rows.Count <= 0) Then Return
FlatTextBox1.Text = String.Empty
FlatTextBox2.Text = String.Empty
FlatTextBox3.Text = String.Empty
RichTextBox1.Text = String.Empty
Dim indx As String = DataGridView1(1, DataGridView1.SelectedRows(0).Index).Value.ToString
Dim dt As DataTable = New DBConnect().selectdata(String.Format("SELECT famille3.Article, famille3.quantité, famille3.prixch, famille3.prixvn, famille3.dateex, famille3.description FROM famille3 where famille3.ID = {0} ", indx))
If dt.Rows.Count > 0 Then
FlatTextBox1.Text = dt.Rows(0)(0).ToString
FlatTextBox2.Text = dt.Rows(0)(1).ToString
FlatTextBox3.Text = dt.Rows(0)(2).ToString
FlatTextBox9.Text = dt.Rows(0)(3).ToString
FlatTextBox10.Text = (dt.Rows(0)(3).ToString - dt.Rows(0)(2).ToString) * dt.Rows(0)(1).ToString
FlatTextBox11.Text = dt.Rows(0)(4).ToString
RichTextBox1.Text = dt.Rows(0)(5).ToString
End If
dt = Nothing
Catch ex As Exception
End Try

I think the stack is here

Dim indx As String = DataGridView1(1, DataGridView1.SelectedRows(0).Index).Value.ToString

How can I resolve it?

Answer Source

In a CellClick event of a DataGridView you receive a parameter of type DataGridViewCellEventArgs. This parameter contains the ColumnIndex and the RowIndex of the clicked cell. So getting the value of the column 1 of the clicked row is really simple as

Sub DataGridView1_CellClick(sender as Object,e As DataGridViewCellEventArgs)
    Dim indx As Integer = Convert.ToInt32(DataGridView1(1, e.RowIndex).Value)

Notice that I have applied a Convert.ToInt32 to the value of the first column. I assume that this is the numeric primary key to find your record. Remember that VB.NET allows you to freely convert string to numbers (VB6 compatibility) but in general this is considered a bad practice. Check your project properties and set Option Strict On instead and you will be forced to improve your code.

Another advice that I feel to give is to not write query in that way. This method is called sql string concatenation and it is the root of Sql Injection. (In your current case there is no big risk, but better to take good habits and always use parameterized queries)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download