如何在不使用 GroupBox 的情况下为单选按钮指定值并确定选定的单选按钮 [英] How can I give a radio button a value and determine the selected radio button without using a GroupBox
问题描述
我有一个包含几个单选按钮的表单,这些单选按钮假设代表不同的整数值.
I have a form with few radio buttons that suppose to represent different integer values.
1) 是否有内置方法可以将值放在单选按钮后面"?一个例子:
1) Is there a built-in way to put a value "behind" a radio button? an example:
RadioButton rad = new RadioButton();
rad.Value = 5; // This is what im trying to achieve.
2) 我有几个单选按钮在逻辑上相互关联,我想知道选择了哪个单选按钮(没有将它们放入 GroupBox 控件中)并获取该单选按钮的选定值.注意:我想迭代"这 3 个控件并获取选定的控件,而不是执行 3 个 IF 语句.一个例子:
2) I have few RadioButtons that are logically related to each other and i want to know which one was selected (without putting them inside a GroupBox control) and get the selected value for that RadioButton. note: I would like to "Iterate" these 3 controls and get the selected one instead of doing 3 IF statements. an example:
RadioButton radColor1 = new RadioButton();
RadioButton radColor2 = new RadioButton();
RadioButton radColor3 = new RadioButton();
// ...
RadioButton radSelected = ?? // Get selected Radio Button from the 3 above.
//here i can get to radSelected.Value
推荐答案
如果要为控件分配任意值,请使用其 Tag
属性:
If you want to assign an arbitrary value to the control, use its Tag
property:
radColor1.Tag = 5;
但是为什么不能简单地使用 Checked
属性?
But why can't you simply use the Checked
property?
if (radColor1.Checked)
//do something
if (radColor2.Checked)
//do something else
//...however many more you need to check
迭代...
foreach (Control c in this.Controls)
{
if (c is RadioButton)
{
if (((RadioButton)c).Checked)
//do something
}
}
这篇关于如何在不使用 GroupBox 的情况下为单选按钮指定值并确定选定的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!