簡體   English   中英

C#-如果在GroupBox中選擇了單選按鈕,請在其他GroupBox中取消選擇其他單選按鈕

[英]C# - If A Radiobutton Selected In GroupBox, Unselect Other Radiobuttons In Other GroupBoxes

我的項目中有11個GroupBox和40個RadioButton。 我想在GroupBox中選擇一個RadioButton時,取消選擇其他GroupBox中的其他RadioButtons。

您可以遞歸地在“表單”中搜索所有RadioButton,然后將它們連接起來並使用注釋中鏈接問題中建議的代碼。

它可能看起來像:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        FindRadioButtons(this);
    }

    private List<RadioButton> RadioButtons = new List<RadioButton>();

    private void FindRadioButtons(Control curControl)
    {
        foreach(Control subControl in curControl.Controls)
        {
            if (subControl is RadioButton)
            {
                RadioButton rb = (RadioButton)subControl;
                rb.CheckedChanged += Rb_CheckedChanged;
                RadioButtons.Add(rb);
            }
            else if(subControl.HasChildren)
            {
                FindRadioButtons(subControl);
            }
        }
    }

    private void Rb_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton source = (RadioButton)sender;
        if (source.Checked)
        {
            RadioButtons.Where(rb => rb != source).ToList().ForEach(rb => rb.Checked = false);
        }          
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM