asp.net - 获取radiobutton组中所选项目的文本

时间:2011-02-01 12:08:31

标签: asp.net vb.net radio-button groupname

我发现了这段代码,但我想知道是否有更简化的方法来实现它。

例如,不是让所有的if语句都有一行代表Label1.text =“你选择了”& RadioGroup1.Text

  Sub SubmitBtn_Click(Sender As Object, e As EventArgs)
     If Radio1.Checked Then
        Label1.Text = "You selected " & Radio1.Text
     ElseIf Radio2.Checked Then
        Label1.Text = "You selected " & Radio2.Text
     ElseIf Radio3.Checked Then
        Label1.Text = "You selected " & Radio3.Text
     End If
  End Sub

   <asp:RadioButton id=Radio1 Text="Typical" Checked="True" GroupName="RadioGroup1" runat="server" />

   <asp:RadioButton id=Radio2 Text="Compact" GroupName="RadioGroup1" runat="server"/>

   <asp:RadioButton id=Radio3 Text="Full" GroupName="RadioGroup1" runat="server" />

   <asp:Button text="Submit" OnClick="SubmitBtn_Click" runat=server/>

   <asp:Label id=Label1 Font-Bold="true"  runat="server" />

3 个答案:

答案 0 :(得分:4)

您可以使用<asp:radiobuttonlist>将其ID设为radio1。然后在那里分开<asp:listitem>。使用不同的value设置每个列表项,即“典型”,“联系人”,“完整”。然后,SubmitBtn_Click中您需要的只是radio1.SelectedItem.Value

答案 1 :(得分:1)

RadioButtonList将有助于减少代码:

<p>
    <strong>Output:</strong>
    <asp:Label runat="server" ID="lOut" />
</p>
<asp:RadioButtonList runat="server" ID="rblist1" AutoPostBack="true"     onselectedindexchanged="rblist1_SelectedIndexChanged"  >
    <asp:ListItem Value="1">One</asp:ListItem>
    <asp:ListItem Value="2">Two</asp:ListItem>
    <asp:ListItem Value="3">Three</asp:ListItem>
</asp:RadioButtonList>


protected void rblist1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.lOut.Text = string.Format("RadioButton: selected: {0}={1} ", rblist1.SelectedItem.Text, rblist1.SelectedValue);
}

答案 2 :(得分:0)

string valueName = Radio3.Text;