C# 如何从 RadioButtonList 中获取选定的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/378620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the selected value from RadioButtonList?
提问by
I have a RadioButtonList on my page that is populated via Data Binding
我的页面上有一个 RadioButtonList 是通过数据绑定填充的
<asp:RadioButtonList ID="rb" runat="server">
</asp:RadioButtonList>
<asp:Button Text="Submit" OnClick="submit" runat="server" />
How do I get the value of the radio button that the user selected in my "submit" method?
如何获取用户在我的“提交”方法中选择的单选按钮的值?
回答by terjetyl
Using your radio button's ID, try rb.SelectedValue
.
使用单选按钮的 ID,尝试rb.SelectedValue
。
回答by azamsharp
The ASPX code will look something like this:
ASPX 代码如下所示:
<asp:RadioButtonList ID="rblist1" runat="server">
<asp:ListItem Text ="Item1" Value="1" />
<asp:ListItem Text ="Item2" Value="2" />
<asp:ListItem Text ="Item3" Value="3" />
<asp:ListItem Text ="Item4" Value="4" />
</asp:RadioButtonList>
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />
And the code behind:
以及背后的代码:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue = rblist1.SelectedValue;
Response.Write(selectedValue);
}
回答by Pushkar Phule
radiobuttonlist.selected <value>
to process with your code.
radiobuttonlist.selected <value>
使用您的代码进行处理。
回答by dizad87
string radioListValue = RadioButtonList.Text;
回答by Leon Faircloth
Technically speaking the answer is correct, but there is a potential problem remaining.
string test = rb.SelectedValue
is an object and while this implicit cast works. It may not work correction if you were sending it to another method (and granted this may depend on the version of framework, I am unsure) it may not recognize the value.
从技术上讲,答案是正确的,但还有一个潜在的问题。
string test = rb.SelectedValue
是一个对象,虽然这个隐式转换有效。如果您将其发送到另一种方法,它可能无法更正(并且这可能取决于框架的版本,我不确定)它可能无法识别该值。
string test = rb.SelectedValue; //May work fine
SomeMethod(rb.SelectedValue);
where SomeMethod
is expecting a string may not.
在哪里SomeMethod
期待一个字符串可能不会。
Sadly the rb.SelectedValue.ToString();
can save a few unexpected issues.
可悲的是,这可以避免rb.SelectedValue.ToString();
一些意想不到的问题。