How can I find the selected RadioButton#39;s value in ASP.NET?(如何在 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 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 ASP.NET 中找到所选 RadioButton 的值?
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01