Error handling - No row at position 0 - Need code to ignore row when no data is found

Tinshooter

Member
Joined
Oct 6, 2011
Messages
6
Programming Experience
1-3
Hey guys, Here is my issue, I have a delete button in a datagridview. The button works fine however when there is nothing to delete it throws an index out of range exception. Now I know for a fact people are going to click that button even though there is nothing there so I guess what I need help with is error handling; I am presuming the best course of action is going to be a try/catch but I am not sure how to do it. My code is as follows, any help would be greatly appreciated, oh and if I am posting this in the wrong place I apologize.



Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.ColumnIndex <> 7 Then
Exit Sub
End If
VoicemailDataSet.Message.Rows(DataGridView1.CurrentRow.Index).Delete()
MessageTableAdapter.Update(VoicemailDataSet.Message)
End Sub
 
No, the best course of action is not going to be a Try/Catch. The best course of action is always prevention over cure. Yopu already know the answer to your question because you're basically already doing it. You're already checking a condition, i.e. that the cell is at particular column index, before deleting. If there's some other condition required then check that condition first too.
 
Would this work?


VB.NET:
If e.ColumnIndex = -1 Then
   Exit Sub
Else
   VoicemailDataSet.Message.Rows(DataGridView1.Curren tRow.Index).Delete()
   MessageTableAdapter.Update(VoicemailDataSet.Messag e)
End If


If not, you can try placing code in the button's Enter event. Or simply disable the button if the list is empty, and reenable it when something is added to the list.
 
I think I figured out what the problem was, I had "enable deleting/adding" inside the datagridview which I think is was throwing everything out of whack since I was coding it myself on the backend, once I disabled it and ran it again and deleted all the rows, there was nothing else there to delete so the exception was not there anymore. Thanks jmcilhinney for cluing me in that I was already doing it...

Thanks Solitare for the help as well, I do appreciate it.
 
Back
Top