开发者

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 DataCont开发者_Python百科rolRowState.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?


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜