首页 > 解决方案 > 选择下拉列表项时自动选择单选按钮,反之亦然

问题描述

我有 4 个单选按钮和一个包含 4 个项目的下拉列表。当我检查单选按钮时,我想从下拉列表中选择适当的项目,当我从下拉列表中选择项目时,我想检查相应的单选按钮。如何在 Windows 窗体中的 C# 中制作它?

我试过了:

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    comboBox1.SelectedItem = "Option1"; 
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    int SelIndex = comboBox1.SelectedIndex;
    switch (SelIndex)
    {
        case 0:
            radioButton1.Checked = true;
            break;
     ....

标签: c#winforms

解决方案


这是一个简单的答案。让所有 RadioButtons 触发相同的事件,然后:

    private void radioButtonAll_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton rb = (RadioButton)sender;
        if (rb.Checked)
        {
            String number = rb.Name.Remove(0, "radioButton".Length);
            String option = "Option" + number;
            if (comboBox1.SelectedItem.ToString() != option)
            {
                comboBox1.SelectedItem = option;
            }
        }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedIndex != -1)
        {
            String number = comboBox1.SelectedItem.ToString().Remove(0, "Option".Length);
            RadioButton rb = this.Controls.Find("radioButton" + number, true).FirstOrDefault() as RadioButton;
            if (rb!=null && !rb.Checked)
            {
                rb.Checked = true;
            }
        }
    }

推荐阅读