Click here to Skip to main content
15,912,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to show and hide groupbox when combobox item index change

if (this.cmbMet.SelectedIndexChanged != null)
         {
             grpMetName.Visible = true;

         }
      else 
         {
            grpMetName.Visible = false;
         }


I'm getting error. Bear in mind, I'm still new to .NET framework and C#. Thank you
Posted
Comments
abbaspirmoradi 12-Oct-13 12:21pm    
in Winforms or Wpf?
arave0521 12-Oct-13 12:55pm    
winforms

You're doing it wrong. SelectedIndexChanged is an event on the ComboBox. You can check if an event is null, but all that tells you is if one or more delegates have been attached to it.

You didn't say exactly what you're trying to accomplish. You also didn't say what the error is. The lack of information makes it hard to help you. But, I'll assume you're trying to show the GroupBox if an item is selected from the ComboBox.

1. Add an event handler for the SelectedIndexChanged event. You can do this from the Windows Forms designer. But, you can also do it in code like this:
C#
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;


2. Add the function that handles the event
C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    bool hasSelection = (comboBox1.SelectedIndex >= 0);
    groupBox1.Visible = hasSelection;
}
 
Share this answer
 
ComboBox SelectedIndexChanged is an EventHandler: it is triggered/fired/invoked anytime the run-time user changes the Selected Item in a ComboBox. If you write this:
C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    groupBox1.Visible = true;
}
Then, every time the user changes the Selected Item in the ComboBox, the GroupBox will have its Visible Property set to 'true. That's probably not what you want.

My guess is that you want the GroupBox made visible only if one Item is selected in the ComboBox, and hidden if any other Item is selected.
C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    groupBox1.Visible = comboBox1.SelectedIndex == 0;

    switch (comboBox1.SelectedIndex)
    {
        case 0:
            // more things to do if the first Item is selected
            break;
        case 1:
            // stuff to do if Item two is selected
            break;
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900