Default Selected Item In A Combo Problems

Hi,

I have a SelectedIndexChanged event handler for a combo so that if the user changes his selection a child window is spawned.

However I also want to set a default value for the combo box e.g. using this code:
comboX.SelectedIndex=0;

Is there a way to set the default without firing the associated event (or perhaps a better way of doing this)?

Thanks!

[366 byte] By [huysmans] at [2007-12-24]
# 1

Everyone's had this problem at some time.

Some options:

Set the selected index before adding the event handler (not possible if you are adding the event handler in designer generated code).

If the event is a method in the same class that the index is set, add a boolean field called "settingUp" or similar, set it to be true during initialization. In the event handler, only do your custom action when settingUp is false.

JimBlackler at 2007-8-31 > top of Msdn Tech,Windows Forms,Windows Forms General...
# 2

some sample code to illustrate what Jim said

1. in designer.cs, you set the initial value

this.comboBox1.SelectedIndex = 0;

2. in form.cs, add event handler after all the components have been initialized

public Form1() {
InitializeComponent();

this.comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
}

void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {

// Create a new form for what is selected

}

gqlu at 2007-8-31 > top of Msdn Tech,Windows Forms,Windows Forms General...