问题描述
如何检查单选按钮列表中的单选按钮是否被选中?
我使用 if radiobuttonlist1.selectedindex > -1 然后我检查了一个单选按钮,但它没有读取选定的单选按钮,它总是转到 else 语句。
这是我的代码:
Dim rl1 As RadioButtonList = New RadioButtonList()
If rbl1.Selectedindex > -1
Label2.Text = "Checked"
Else
Label2.Text = "Not Checked"
End If
解决方法
你可以这样做。
转到您的 RadioButton_CheckedChanged
事件并添加此代码
If RadioButton1.Checked = True Then
Me.Label1.Text = "Checked"
Else
Me.Label1.Text = "UnChecked"
End If
,
您在代码中使用了正确的变量名称吗?您正在声明 rl1 但正在验证 rbl1。如果不是这种情况,请检查以下代码是否有帮助:
Dim rl1 As RadioButtonList = New RadioButtonList()
'Just adding some items and selecting one of them for demonstration
rl1.Items.Add(New ListItem("Option 1","1"))
rl1.Items.Add(New ListItem("Option 2","2"))
rl1.SelectedIndex = 1
If rl1.SelectedIndex > -1 Then
MsgBox("Checked")
Else
MsgBox("Not Checked")
End If
,
Dim rl1 As RadioButtonList = New RadioButtonList()
所以你创建了上面的内容?上面的内容是怎么知道的或者跟网页有什么关系的?您在代码中创建的某些变量与您在网页上拥有的控件之间的关系为零吗?
你想要
MyRadioButtonOnTheWebPage.Selectedindex
大概是这样:
RadioButtonList1.Selected 索引。
因此,您不会突然创建并变暗一些与实际网页上的实际单选按钮列表无关的变量。我的意思是,如果您的网页上有 3 个 RadioButton 列表,上面指的是哪一个?
因此,如果您有这样的 Radiobuttion 列表“1”:
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"
RepeatDirection="Horizontal">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Tow</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
</asp:RadioButtonList>
然后是按钮回发,或者甚至说为单选按钮列表设置 autopostback = true。
然后在代码中你可以使用:
Debug.Print(RadioButtonList1.SelectedIndex)
Debug.Print(RadioButtonList1.SelectedValue)
所以上面会得到索引值,或者单选按钮的实际值。
如果您有 auto postback = true,那么您可以/将使用这样的事件(已更改),当您在单选按钮中选择/更改选择时将触发该事件
Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object,e As EventArgs) Handles RadioButtonList1.SelectedIndexChanged
Debug.Print(RadioButtonList1.SelectedIndex)
Debug.Print(RadioButtonList1.SelectedValue)
End Sub