寻找在ASP.NET中所选RadioButton的价值 [英] Finding the selected Radiobutton's value in ASP.NET

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

问题描述

编码平台:ASP.NET 4.0的WebForms用C#

Coding Platform: ASP.NET 4.0 WebForms with C#

我有两个的asp:单选它们具有相同组名基本上使它们互相排斥的控制。

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"/>

我的目的是发现被检查的单选按钮的提示/文本。结果
现在,我编码类似这样

My intention was to find the tooltip / text of the RadioButton that is checked.
Now, I am coding like this

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

我发现,code丑陋和冗余。 (如果我有什么20复选框?)

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

是否有会得到一个方法从一组单选按钮的检查单选相同的组名?如果不是,什么是三分球上写的?

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

P.S:在这种情况下不能使用一个单选按钮列表

P.S: 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.

更新

如果你想确保你得到单选按钮与同组,你有两个选择:

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


  • 让他们在不同的容器

  • 添加组过滤器的lamdba前pression,所以它看起来是这样的:

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

RB =&GT; rb.Checked&功放;&安培; rb.GroupName ==YourGroup

更新2

修改了code,以确保它,如果没有选中单选按钮不会失败多一点失败的证明。

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天全站免登陆