Home > OS >  Change ComboBox Enabled State based on the in another ComboBox C#
Change ComboBox Enabled State based on the in another ComboBox C#

Time:09-24

I have two ComboBoxs 1st with CmdGuarantor and the 2nd with CmdGuarantorClass as names. CmdGuarantor has a list of 7 items:

NSSF Private MOH Army IS GS UNHCR while CmdGuranatorClass has 1st Class 2nd Class 3rd Class in its items list.

I want to disable CmdGuarantorClass whenever CmdGuarator.SelectedItem.ToString() == "Private" || CmdGuarator.SelectedItem.ToString() == "UNCHR"

how can I accomplish that?

P.S.: I tried using the EnableChanged event on CmdGuarantorClass ComboBox using this method

    private void ComboBox2_EnabledChanged(object sender, EventArgs e)
    {
        if (CmdGuarantor.SelectedItem.ToString() == "Private" || CmdGuarantor.SelectedItem.ToString() == "UNCHR")
        {
            CmdGuarantorClass.Enabled = false;
        }
        else CmdGuarantorClass.Enabled = true;
    }

but with no luck.

thank you in advance.

CodePudding user response:

You should be listening for the SelectionChanged event, not the EnabledChanged event. EnabledChanged is only raised when the IsEnabled property is changed.

CodePudding user response:

Assuming the datagridview tag is a mistake and you are talking about two different winform ComboBoxes… then… I suggest you wire up the first combo boxes SelectedIndexChanged event.

This event will fire when the user changes the selection in the combo box. In that event you can check the combo box values as you have done and then set the other combo boxes Enabled property as needed. Something like…

private void comboGuarantor_SelectedIndexChanged(object sender, EventArgs e) {
  if (comboGuarantor.SelectedItem.ToString() == "Private" ||
      comboGuarantor.SelectedItem.ToString() == "UNCHR") {
    comboGuarantorClass.SelectedIndex = -1;
    comboGuarantorClass.Enabled = false;
  }
  else {
    comboGuarantorClass.Enabled = true;
  }
}
  • Related