该组中哪个单选按钮被选中?

132

使用WinForms;有没有更好的方法来查找群组中选中的RadioButton?我认为下面的代码不应该是必要的。当您选择不同的RadioButton时,它知道应取消哪一个……因此它应该知道哪个已被选中。如何在不进行大量if语句(或switch)的情况下获取该信息。

     RadioButton rb = null;

     if (m_RadioButton1.Checked == true)
     {
        rb = m_RadioButton1;
     }
     else if (m_RadioButton2.Checked == true)
     {
        rb = m_RadioButton2;
     }
     else if (m_RadioButton3.Checked == true)
     {
        rb = m_RadioButton3;
     }

1
底层代码不知道要取消哪个,它只会迭代更改的控件同一级别父控件下面的所有RadioButton控件,并取消选中以前选定的那个。 - João Angelo
1
你是在使用WinForms还是ASP.Net? - SLaks
14个回答

0
如果您想获取控件中所选单选按钮的索引,可以使用以下方法:
public static int getCheckedRadioButton(Control c)
{
    int i;
    try
    {
        Control.ControlCollection cc = c.Controls;
        for (i = 0; i < cc.Count; i++)
        {
            RadioButton rb = cc[i] as RadioButton;
            if (rb.Checked)
            {
                return i;
            }
        }
    }
    catch
    {
        i = -1;
    }
    return i;
}

使用示例:

int index = getCheckedRadioButton(panel1);

代码测试不是很充分,但似乎索引顺序是从左到右、从上到下的,就像阅读文本一样。如果没有找到单选按钮,则该方法返回-1。

更新:事实证明,如果控件内没有单选按钮,我的第一次尝试是无效的。我添加了一个try和catch块来修复这个问题,现在该方法似乎可以工作了。


0

针对使用VB.NET的开发人员


Private Function GetCheckedRadio(container) As RadioButton
    For Each control In container.Children
        Dim radio As RadioButton = TryCast(control, RadioButton)

        If radio IsNot Nothing AndAlso radio.IsChecked Then
            Return radio
        End If
    Next

    Return Nothing
End Function

0

如果您正在使用WinForms,GroupBox有一个Validated事件可用于此目的。

private void grpBox_Validated(object sender, EventArgs e)
    {
        GroupBox g = sender as GroupBox;
        var a = from RadioButton r in g.Controls
                 where r.Checked == true select r.Name;
        strChecked = a.First();
     }

0

再试一次 - 使用事件 Lambda 表达式

当表单初始化时,可以将单个事件处理程序分配给组合框中所有类型为 RadioButton 的控件,并使用 .tabIndex 或 .tag 属性来标识选项在更改时被选中的内容。

这样,您就可以一次性订阅每个单选按钮的任何事件。

int priceOption = 0;
foreach (RadioButton rbtn in grp_PriceOpt.Controls.OfType<RadioButton>())
{
    rbtn.CheckedChanged += (o, e) =>
    {
        var button = (RadioButton)o;
        if (button.Checked)
        {
            priceOption = button.TabIndex;
        }
    };
}

由于事件仅分配给单选按钮,因此未实现发送方的类型检查。

另请注意,当我们循环所有按钮时,这可能是分配数据属性,更改文本等的完美时刻。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接