【发布时间】:2017-11-08 12:48:00
【问题描述】:
所以我有两个组框,我想要的是从它们中获取选定的单选按钮值。
如果它只是一个文本框你可以去:
thisValue = textbox1.text
但我不知道如何为单选按钮执行此操作
【问题讨论】:
-
你实际处理的是什么课?
标签: c# winforms radio-button
所以我有两个组框,我想要的是从它们中获取选定的单选按钮值。
如果它只是一个文本框你可以去:
thisValue = textbox1.text
但我不知道如何为单选按钮执行此操作
【问题讨论】:
标签: c# winforms radio-button
要从单选按钮中获取值(假设您想要 值,而不是文本),您将获得 Checked 属性:
bool isChecked = radioButton1.Checked;
GroupBox 中的单选按钮之间没有基于代码的关系(除了单选按钮的行为方式使得一次只检查同一容器中的一个单选按钮);您的代码将需要跟踪检查了哪一个。
最简单的方法可能是使组框中的单选按钮都为CheckedChanged 事件触发相同的事件侦听器。在这种情况下,您可以检查 sender 参数以跟踪当前选择了哪一个。
例子:
private enum SearchMode
{
TitleOnly,
TitleAndBody,
SomeOtherWay
}
private SearchMode _selectedSearchMode;
private void SearchModeRadioButtons_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
if (rb.Checked)
{
if (rb == _radioButtonTitleOnly)
{
_selectedSearchMode = SearchMode.TitleOnly;
}
else if (rb == _radioButtonTitleAndBody)
{
_selectedSearchMode = SearchMode.TitleAndBody;
}
else
{
// and so on
}
}
}
【讨论】:
这是 WindowsForms Linq 示例 如果它不能完全发挥作用,你会明白的
RadioButton rb = null;
RadioButton checkedRB = groupBox1.Controls.FirstOrDefault(
c => (rb = c as RadioButton) != null && rb.Checked) as RadioButton;
if (checkedRB != null)
{
this.Text = checkedRB.Text;
}
【讨论】:
引用同一个点击事件触发器
private void rb_Click(object sender, EventArgs e) {
thisValue = ((RadioButton)sender).Text;
}
【讨论】: