如何在ASP.NET中找到所选的RadioButton值?
我有两个asp:RadioButton
控件,它们具有相同的GroupName
,这实际上使它们互斥。
我的标记:
我的目的是找到被检查的RadioButton的工具提示/文本。 我有这个代码隐藏:
int registrationTypeAmount = 0; if (OneJobPerMonthRadio.Checked) { registrationTypeAmount = Convert.ToInt32(OneJobPerMonthRadio.ToolTip); } if (TwoJobsPerMonthRadio.Checked) { registrationTypeAmount = Convert.ToInt32(TwoJobsPerMonthRadio.ToolTip); }
我发现代码丑陋且多余。 (如果我有20个复选框怎么办?)
有没有一种方法可以从一组具有相同GroupName
的RadioButton中获取已检查的RadioButton
? 如果没有,写一个的指针是什么?
PS:我不能在这种情况下使用RadioButtonList
。
你想这样做:
RadioButton selRB = radioButtonsContainer.Controls.OfType().FirstOrDefault(rb => rb.Checked); if(selRB != null) { int registrationTypeAmount = Convert.ToInt32(selRB.ToolTip); string cbText = selRB.Text; }
其中radioButtonsContainer是radiobuttons的容器。
更新
如果您想确保让RadioButtons具有相同的组,您有两个选择:
- 将它们放在单独的容器中
-
将组filter添加到lamdba表达式,因此它看起来像这样:
rb => rb.Checked && rb.GroupName == "YourGroup"
更新2
通过确保在没有选择RadioButton的情况下确保它不会失败,修改了代码以使其更加失败。
您可以尝试写下类似的方法:
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; }
然后,您可以像这样调用方法:
RadioButton selectedRadio = GetSelectedRadioButton(OneJobPerMonthRadio, TwoJobsPerMonthRadio);
它将返回所选的一个(如果有的话),无论你有多少个单选按钮,它都能正常工作。 您可以重写该方法,以便在需要时返回SelectedValue。