作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有两个 asp:RadioButton
控件,它们具有相同的 GroupName
,这实际上使它们相互排斥。
我的标记:
<asp:RadioButton ID="OneJobPerMonthRadio" runat="server"
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="125"/>
<asp:RadioButton ID="TwoJobsPerMonthRadio" runat="server"
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="200"/>
我的目的是找到选中的 RadioButton 的工具提示/文本。我有这个代码隐藏:
int registrationTypeAmount = 0;
if (OneJobPerMonthRadio.Checked)
{
registrationTypeAmount = Convert.ToInt32(OneJobPerMonthRadio.ToolTip);
}
if (TwoJobsPerMonthRadio.Checked)
{
registrationTypeAmount = Convert.ToInt32(TwoJobsPerMonthRadio.ToolTip);
}
我发现该代码丑陋且多余。 (如果我有 20 个复选框怎么办?)
是否有一种方法可以从一组具有相同 GroupName
的 RadioButton 中获取选中的 RadioButton
?如果没有,写一个有什么建议?
P.S:在这种情况下我不能使用 RadioButtonList
。
最佳答案
你想这样做:
RadioButton selRB = radioButtonsContainer.Controls.OfType<RadioButton>().FirstOrDefault(rb => rb.Checked);
if(selRB != null)
{
int registrationTypeAmount = Convert.ToInt32(selRB.ToolTip);
string cbText = selRB.Text;
}
其中 radioButtonsContainer 是单选按钮的容器。
更新
如果您想确保获得同一组的 RadioButton,您有 2 个选择:
将它们放在不同的容器中
将组过滤器添加到 lamdba 表达式中,如下所示:
rb => rb.Checked && rb.GroupName == "YourGroup"
更新 2
修改了代码以确保在未选择 RadioButton 时不会失败,从而使其更具防错性。
关于c# - 如何在 ASP.NET 中找到选定的 RadioButton 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732540/
我是一名优秀的程序员,十分优秀!