如何在ASP.NET中找到选定的RadioButton的值? [英] How can I find the selected RadioButton's value in ASP.NET?

查看:534
本文介绍了如何在ASP.NET中找到选定的RadioButton的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个asp:RadioButton控件,它们具有相同的GroupName,这实际上使它们相互排斥.

I have two asp:RadioButton controls which are having the same GroupName which essentially makes them mutually exclusive.

我的标记:

<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的工具提示/文本.我的代码在后面:

My intention was to find the tooltip / text of the RadioButton that is checked. I have this code-behind:

int registrationTypeAmount = 0;
if (OneJobPerMonthRadio.Checked)
{
    registrationTypeAmount = Convert.ToInt32(OneJobPerMonthRadio.ToolTip);
}
if (TwoJobsPerMonthRadio.Checked)
{
    registrationTypeAmount = Convert.ToInt32(TwoJobsPerMonthRadio.ToolTip);
}

我发现该代码难看且多余. (如果我有20个复选框,该怎么办?)

I find that code ugly and redundant. (What if I have 20 checkboxes?)

是否有一种方法可以从具有相同GroupName的一组RadioButton中获取已检查的RadioButton?如果没有,那么写一个的指针是什么?

Is there a method that would get the checked RadioButton from a set of RadioButtons with the same GroupName? And if not, what are the pointers on writing one?

P.S:在这种情况下,我不能使用RadioButtonList.

P.S: I cannot use a RadioButtonList in this scenario.

推荐答案

您要执行以下操作:

RadioButton selRB = radioButtonsContainer.Controls.OfType<RadioButton>().FirstOrDefault(rb => rb.Checked);
if(selRB != null)
{
    int registrationTypeAmount = Convert.ToInt32(selRB.ToolTip);
    string cbText = selRB.Text;
}

其中radioButtonsContainer是单选按钮的容器.

where radioButtonsContainer is the container of the radiobuttons.

更新

如果要确保您获得的RadioButton具有相同的组,则有两个选项:

If you want to ensure you get RadioButtons with the same group, you have 2 options:

  • 将它们放在单独的容器中
  • 将组过滤器添加到lamdba表达式中,因此看起来像这样:

  • Get them in separate containers
  • Add the group filter to the lamdba expression, so it looks like this:

rb => rb.Checked && rb.GroupName == "YourGroup"

更新2

修改了代码,通过确保在未选择RadioButton的情况下也不会失败来使它更加可靠.

Modified the code to make it a little more fail proof by ensuring it won't fail if there's no RadioButton selected.

这篇关于如何在ASP.NET中找到选定的RadioButton的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆