如果GridViewRow被选中那么......其他

时间:2010-12-23 00:22:41

标签: asp.net vb.net gridview rowstate

好吧,这看起来应该很容易,但是我似乎无法正常工作而不会出错。我有一个IfThen语句,声明是否选择了一行,然后执行,否则显示消息。如果我选择一行,代码运行正常,但是当我尝试继续而不选择行时,我得到一个错误而不是我想要显示的消息。这是我正在尝试做的一个例子:

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

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

正如Miguel已经提到的,当没有选择行时,SelectedRow属性不返回任何内容。所以你必须检查一下:

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

您还可以检查SelectedIndex是否为<> -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

答案 1 :(得分:0)

如果没有选择行,这是不是意味着“行”将被评估为Nothing,所以当你试图得到它的RowState时你会得到一个错误,因为没有什么不能有RowStates?

我会检查它是否是这样的:

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