C# 中单选按钮的文本框 enable/disable

TextBox enable/disable by radiobutton in C#

我在 Winform 中有 4 个单选按钮,其中一个单选按钮 (radiobutton_4) 是触发器以启用运行良好的文本框。但如果在选中触发单选按钮后更改任何其他单选按钮,文本框将不会更改禁用。enter image description here

触发单选按钮

    private void radioButton4_CheckedChanged(object sender, EventArgs e)
    {
        Radioctrlvalue = "fromvalue";
        textBox1.Enabled = true;
        textBox2.Enabled = true;
        textBox3.Enabled = true;
    }

其他单选按钮

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
      // if projectbase point radio is checked and string variable store 
      Radioctrlvalue = "projectpoint";
        textBox1.Enabled = false;
        textBox2.Enabled = false;
        textBox3.Enabled = false;
    }

enter image description here

如果你想要 textBox1 .. textBox3 应该 禁用 当且仅当 radioButton1.Checked 你可以分配 !radioButton1.Checked:

// When radioButton1 ("Project BasePoint") Check state changed 
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    textBox1.Enabled = !radioButton1.Checked;
    // textBox2 and textBox3 have the same behavior
    textBox2.Enabled = textBox1.Enabled;
    textBox3.Enabled = textBox1.Enabled;
}

在一般情况下(例如,当且仅当 radioButton4radioButton5Checked 时,textBox1.Enabled 应该是 true),您可以 提取方法:

private void UpdateEnabled() {
  textBox1.Enabled = radioButton4.Checked || radioButton5.Checked;
  textBox2.Enabled = textBox1.Enabled;
  textBox3.Enabled = textBox1.Enabled;
  
  //TODO: Put all the other rules here
}

...

private void radioButton4_CheckedChanged(object sender, EventArgs e) {
  Radioctrlvalue = "fromvalue";
 
  UpdateEnabled();
}

private void radioButton5_CheckedChanged(object sender, EventArgs e) {
  //TODO: Relevant code here
 
  UpdateEnabled();
}

每次更改单选按钮状态时,所有附加到每个单选按钮的 CheckedChanged 函数都会执行,即使状态更改为 false。您应该在函数中检查状态并仅在状态为“已检查”时才执行您的代码。

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if((sender as radioButton).Checked)
    {
        textBox1.Enabled = false;
    }     
}

private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    if((sender as radioButton).Checked)
    {
        textBox1.Enabled = true;
    }     
}

您甚至可以只使用一个函数附加到所有单选按钮处理所有变体。例如,将 RadioButton1.Tag 值设置为 false,将 RadioButton2.Tag 值设置为 true 并在代码中使用它。

private void AllRadioButtons_CheckedChanged(object sender, EventArgs e)
{
    if((sender as radioButton).Checked)
    {
        textBox1.Enabled = (bool)((sender as radioButton).Tag);
    }     
}