WinForms manually calling SelectedIndexChanged on combobox

  • Thread starter Thread starter GiJeet
  • Start date Start date
G

GiJeet

Hello, I'd like to force a call to the SelectedIndexChanged of a combo
box from within a method. I tried to just call it like so:
this.myComboBox.SelectedIndexChanged; but of course the event takes 2
parameters - object sender, EventArgs e and not sure how to pass these
paras from my method. Should I just make up fake ones to pass?

Any help would be appreciated.

G
 
GiJeet,

You aren't going to be able to do it. Events can only be called by the
instance itself, you don't have access to the delegates and won't be given
access to them to call.
 
GiJeet, at the time you're in the method, the SelectedIndexChanged event
handler has already been called when it was set to whatever value it holds
at the time.

You CAN actually call it yourself like this:

this.comboBox1_SelectedIndexChanged(this.comboBox1, new EventArgs());

but remember that it's already been called once for the current value.

The fact that you are wanting to do this makes me suspect that you may have
code in the SelectedIndexChange event handler that should possibly be
refactored out into a separate private method on the form. Having done so,
you could freely call it from wherever you want.

Tom Dacon
Dacon Software Consulting
 
Tom said:
The fact that you are wanting to do this makes me suspect that you may have
code in the SelectedIndexChange event handler that should possibly be
refactored out into a separate private method on the form. Having done so,
you could freely call it from wherever you want.

For what it's worth, I sometimes "unsubsribe" from event handlers during
some actions, if these actions also might replace datasources and such
stuff.

After all work is done, I usually re-subscribe to the event, and -
similar to the OP - call the eventhandler "manually" once.

Is there a better approach?
 
The fact that you are wanting to do this makes me suspect that you may have
code in the SelectedIndexChange event handler that should possibly be
refactored out into a separate private method on the form. Having done so,
you could freely call it from wherever you want.

Tom, you are correct, the code in the SelectedIndex event should be
moved out. But I didn't write the code...just fixing some bug and not
sure I want to go thru the exercise of factoring out all the places
that need it. But that is the best move.

I decided to just pass null,null and see what happends
eg: this.MyComboBox_SelectedIndexChanged(null, null);

I'll report back....
G
 
I'll report back....
G

Since I'm not using Sender or EventArgs calling
this.MyComboBox_SelectedIndexChanged(null, null); with the nulls works
ok.
you jump right into the SelectedIndexChanged event.

G
 
Back
Top