如何在 ASP.NET 中找到所选 RadioButton 的值?所选、中找到、如何在、NET

2023-09-06 19:11:04 作者:巫山云雨﹌

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"/>
asp.net datalist中的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);
}

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.