holemania
asked on
VB.NET Datagridview Index out of range error
This may be a very simple fix, but I can't seem to figure this out. I have a query that pull data from a sql database and display it into a datagrid. When it does this, I also want to fill a textbox (txtTime.text) with the first row ("TIME_ID") from the datagrid. However, the query pull empty data, I get the index out of range error.
How would I set my syntax so that if datagrid is empty, exit the sub/function? I tried the following but no luck and still getting index out of range.
How would I set my syntax so that if datagrid is empty, exit the sub/function? I tried the following but no luck and still getting index out of range.
If datagridview1.Rows(0).Cells("TIME_ID").Value = "" Then
EXIT SUB
else
txtTime.text = datagridview1.Rows(0).Cells("TIME_ID").Value
End If
What data type is time_id?
Just change your query to 'and not isnull('time_id')'
Check for NULL instead of ""
ASKER
TIME_ID is an int data type. However, I don't think that's the issue. I am trying to pull TIME_ID from a data grid view into a textbox. Since the datagrid has nothing in it, I am getting index out of range error.
Can I code so that if there's nothing in the datagrid, just to exit the function like the example I provided? I tried that, but still error out at that part. If I fill the table with data, and the query fill the datagridview, then it is fine and I don't get this error. So only time I get an error is if it does not pull data into the datagridview.
Can I code so that if there's nothing in the datagrid, just to exit the function like the example I provided? I tried that, but still error out at that part. If I fill the table with data, and the query fill the datagridview, then it is fine and I don't get this error. So only time I get an error is if it does not pull data into the datagridview.
Or else check in this way
If gridView1.Rows.Count > 0 then
txtTime.text = datagridview1.Rows(0).Cell s("TIME_ID ").Value
Else
Exit Sub
End If
If gridView1.Rows.Count > 0 then
txtTime.text = datagridview1.Rows(0).Cell
Else
Exit Sub
End If
You can also use:
If Me.DataGridView1.RowCount > 0 Then
' your code
End If
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for all the suggestion. I am currently out of the office traveling and won't be able to test until next week. I will look again and update, and distribute points accordingly.
ASKER
Thank you. The example you provided work great.