gpt4 book ai didi

c# - 如何在 ASP.NET 中找到选定的 RadioButton 的值?

转载 作者:可可西里 更新时间:2023-11-01 07:45:44 24 4
gpt4 key购买 nike

我有两个 asp:RadioButton 控件,它们具有相同的 GroupName,这实际上使它们相互排斥。

我的标记:

<asp:RadioButton ID="OneJobPerMonthRadio" runat="server" 
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="125"/>
<asp:RadioButton ID="TwoJobsPerMonthRadio" runat="server"
CssClass="regtype"
GroupName="RegistrationType"
ToolTip="200"/>

我的目的是找到选中的 RadioButton 的工具提示/文本。我有这个代码隐藏:

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

我发现该代码丑陋且多余。 (如果我有 20 个复选框怎么办?)

是否有一种方法可以从一组具有相同 GroupName 的 RadioButton 中获取选中的 RadioButton?如果没有,写一个有什么建议?

P.S:在这种情况下我不能使用 RadioButtonList

最佳答案

你想这样做:

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

其中 radioButtonsContainer 是单选按钮的容器。

更新

如果您想确保获得同一组的 RadioButton,您有 2 个选择:

  • 将它们放在不同的容器中

  • 将组过滤器添加到 lamdba 表达式中,如下所示:

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

更新 2

修改了代码以确保在未选择 RadioButton 时不会失败,从而使其更具防错性。

关于c# - 如何在 ASP.NET 中找到选定的 RadioButton 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com