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.
Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.
Returns true if the radio button is checked by default, otherwise it returns false.
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.
You may try writing down a similar method to the one below:
private RadioButton GetSelectedRadioButton(params RadioButton[] radioButtonGroup)
{
// Go through all the RadioButton controls that you passed to the method
for (int i = 0; i < radioButtonGroup.Length; i++)
{
// If the current RadioButton control is checked,
if (radioButtonGroup[i].Checked)
{
// return it
return radioButtonGroup[i];
}
}
// If none of the RadioButton controls is checked, return NULL
return null;
}
Then, you can call the method like this:
RadioButton selectedRadio =
GetSelectedRadioButton(OneJobPerMonthRadio, TwoJobsPerMonthRadio);
It will return the selected one (if there is) and it will work for no matter how many radio buttons you have. You can rewrite the method, so that it returns the SelectedValue, if you wish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With