events problem

  • Thread starter Thread starter juli
  • Start date Start date
J

juli

Hello,
I am trying to react to a selection change in a combobox which is
filled dynamicly during the run of the program.
I am trying to do the following:
1)Declaring the comboBox
2)Initializing it (it is empty).
3)Filling it with data
private void Fill_Menu()
{
for(int i=0;i<command_name.Count;i++)
{
comboBox.Items.Add(command_name);
}
}

And than inside some other function I am doing the:
this.comboBox.SelectedIndexChanged+=new
EventHandler(comboBox_SelectedIndexChanged);

but the problem is that it activates the event more times than needed
and I understood that I have to put this event inside the OnLoad of
the form function but the problem is that I have no data inside the
combobox at the begginig .How do I solve this problem?
Thank you!
 
You can check wether the combo box is full or not this way:

void comboBox_SelectedIndexChanged(...)
{
if(this.comboBox1.Items.Count > 0)
{
..
..
..
}
}
 
You can use a flag to indicate when you're filling the combo box and
the resulting SelectedIndexChanged events are of no interest to you:

private void Fill_Menu()
{
this.fillingComboBox = true;
for(int i=0;i<command_name.Count;i++)
{
comboBox.Items.Add(command_name);
}
this.fillingComboBox = false;
}

private void comboBox_SelectedIndexChanged(object sender, EventArgs ea)
{
if (!this.fillingComboBox)
{
....react to selected index changed event here...
}
}

Another possible choice is that you could remove/add the event handler
in your fill method:

private void Fill_Menu()
{
this.comboBox.SelectedIndexChanged -= new
EventHandler(comboBox_SelectedIndexChanged);
for(int i=0;i<command_name.Count;i++)
{
comboBox.Items.Add(command_name);
}
this.comboBox.SelectedIndexChanged += new
EventHandler(comboBox_SelectedIndexChanged);
}
 
Back
Top