0

Ok, this seems like it should be very easy to do, however I can't seem to work without erroring out. I have an IfThen Statement that states if a row is selected, then execute, else, display message. The code runs fine if I select a row, however when I try and proceed without selecting a row I get an error instead of the message I want to display. Here is an example of what I'm trying to do:

Protected Sub btnReplace(ByVal sender As Object, ByVal e As EventArgs)

    Dim row As GridViewRow = device_list.SelectedRow

    If (row.RowState Or DataControlRowState.Selected) > 0 Then
        Message.Text = "You selected " & row.Cells(1).Text & "."
    Else
        Message.Text = "Please select a device."
    End If

End Sub

Can anyone help me out with this?

Kevin
  • 111
  • 1
  • 3
  • 10

2 Answers2

1

As Miguel already mentioned, the SelectedRow property returns nothing when no row is selected. So you have to check this:

Dim row As GridViewRow = device_list.SelectedRow
If Not row Is Nothing Then
   Message.Text = "You selected " & row.Cells(1).Text & "."
Else
    Message.Text = "Please select a device."
End If

You can also check if the SelectedIndex is <> -1

 If device_list.SelectedIndex <> -1 Then
    Message.Text = "You selected " & device_list.SelectedRow.Cells(1).Text & "."
 Else
     Message.Text = "Please select a device."
 End If
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

If no row is selected, doesn't that mean "row" would evaluate as Nothing, so you'll get an error when you try to get it's RowState since Nothing can't have RowStates?

I would check if it's Nothing like this:

Protected Sub btnReplace(ByVal sender As Object, ByVal e As EventArgs)

    Dim row As GridViewRow = device_list.SelectedRow

    If (row <> Nothing Or DataControlRowState.Selected) > 0 Then
        Message.Text = "You selected " & row.Cells(1).Text & "."
    Else
        Message.Text = "Please select a device."
    End If

End Sub
Migwell
  • 18,631
  • 21
  • 91
  • 160