i have 4 Radio buttons in Winform and one of radio button(radiobutton_4) is trigger to enable the Textbox which is works well. but if change any other radiobutton after checked the trigger radiobutton the textbox will not change disable.enter image description here
trigger radiobutton
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
Radioctrlvalue = "fromvalue";
textBox1.Enabled = true;
textBox2.Enabled = true;
textBox3.Enabled = true;
}
other radiobutton
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;
}
CodePudding user response:
If you want textBox1
.. textBox3
should be disabled if and only if radioButton1.Checked
you can just assign !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;
}
In general case (when, say, textBox1.Enabled
should be true
if and only if radioButton4
or radioButton5
are Checked
) you can extract a method:
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();
}
CodePudding user response:
Everytime you change radiobuttons state all attached to each radiobutton CheckedChanged functions are executing, even if state changes to false. You should check state in function and execute your code only if state is "checked".
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;
}
}
You can even use only ONE function attached to all radioButtons handling with all variants. For example set RadioButton1.Tag value to false, RadioButton2.Tag value to true and use it in code.
private void AllRadioButtons_CheckedChanged(object sender, EventArgs e)
{
if((sender as radioButton).Checked)
{
textBox1.Enabled = (bool)((sender as radioButton).Tag);
}
}