user3081555 user3081555 - 3 months ago 9
C# Question

using checkbox to enable textbox

i have an application here in winforms that am trying to make. This is how i want it to happen: whenever the user clicks on register visitor button the registration form should be opening. works fine. here is the function that is called in that case:

private void Register_Visitor_Load(object sender, EventArgs e)


On this form i have a textfield placed which i want to disable when the form loads. i wrote a line which disables the textbox on form load:

textbox1.enabled = false;


i placed the above line in the load function which is working fine. now i want to enable my textbox1 based on the checkbox checked. for this i wrote the code:

CheckState state = checkBox1.CheckState;
switch (state)
{
case CheckState.Checked:
{
textBox1.Enabled = true;
break;
}
case CheckState.Indeterminate:
case CheckState.Unchecked:
{
break;
}


now when i place the code above in the page load function nothing happens which is surely going to happen as that function is only called on form load. what am not getting is where to place the checkbox code so that my textbox is enable on runtime. other function are in response to button but what i want here it to instantly enable the textfield on runtime when the user checks the checkbox. kindly explain me how am i going to accomplish this!

Answer

You can use CheckStateChanged event; so whatever reason the checkBox1 is checked/unchecked/grayed you'll have the textBox1 properly enabled/disabled

private void checkBox1_CheckStateChanged(object sender, EventArgs e) {
  textBox1.Enabled = (checkBox1.CheckState == CheckState.Checked);
}
Comments