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

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

问题描述

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

My markup:

<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. I have this code-behind:

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

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 the same GroupName? And if not, what are the pointers on writing one?

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

解决方案

You want to do this:

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

where radioButtonsContainer is the container of the radiobuttons.

Update

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

  • Get them in separate containers

  • Add the group filter to the lamdba expression, so it looks like this:

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

Update 2

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