asp.netvb.netgridviewrowstate

If GridViewRow is Selected Then ... Else


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?


Solution

  • 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