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.


If datagridview1.Rows(0).Cells("TIME_ID").Value = "" Then
       EXIT SUB
else
       txtTime.text = datagridview1.Rows(0).Cells("TIME_ID").Value
End If

Open in new window

holemaniaAsked:
Who is Participating?
 
JackOfPHConnect With a Mentor Commented:
Try the below code...
This will check if the row count in datagridview is zero, If it is zero the code will exit...
If datagridview1.Rows.Count = 0 then
      Exit sub
end if
 
If datagridview1.Rows(0).Cells("TIME_ID").Value = "" Then
       EXIT SUB
else
       txtTime.text = datagridview1.Rows(0).Cells("TIME_ID").Value
End If

Open in new window

0
 
mpeaden2Commented:
What data type is time_id?

0
 
mpeaden2Commented:
Just change your query to 'and not isnull('time_id')'
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
krishrrCommented:
Check for NULL instead of ""
0
 
holemaniaAuthor Commented:
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.
0
 
srikanthreddyn143Commented:
Or else check in this way

If gridView1.Rows.Count > 0 then
txtTime.text = datagridview1.Rows(0).Cells("TIME_ID").Value
Else
Exit Sub
End If
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
You can also use:
        If Me.DataGridView1.RowCount > 0 Then
            ' your code
        End If

Open in new window

0
 
holemaniaAuthor Commented:
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.
0
 
holemaniaAuthor Commented:
Thank you.  The example you provided work great.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.