Kevin
Kevin

Reputation: 111

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?

Upvotes: 0

Views: 4036

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

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

Upvotes: 1

Migwell
Migwell

Reputation: 20147

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

Upvotes: 0

Related Questions