1

I need to call tabControl1_SelectedIndexChanged from Form1 in Form2

I have no idea how do this.

The Mask
  • 17,007
  • 37
  • 111
  • 185

3 Answers3

6

In general, you don't call events from other classes. The idea is that events expose subscribe/unsubscribe behaviour. The implementation can choose to also expose a method which raises the event, but it doesn't have to - and if the control you're using doesn't expose such a method for the SelectedIndexChanged event, you can't force it to.

It's not clear what you're trying to achieve, but you may be able to programmatically select the appropriate tab instead - I'd expect that to raise the appropriate event. Rather than expose the tab control directly from Form1 to Form2 (which I hope are only placeholder names - give your forms meaningful names :) it would be cleaner to expose a method in Form1 to perform the selection of the appropriate tab. That's a more meaningful operation to perform on Form1 - it doesn't rely as heavily on the implementation details. On the other hand, you may be able to create an even cleaner design using MVP patterns (or whatever suits you best).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I did it, worked fine now, thanks again John! I declared tabControl1_SelectedIndexChanged as public instead protected and then: `parentForm.tabControl1_SelectedIndexChanged(null, null);` – The Mask Dec 13 '11 at 17:29
  • 1
    @TheMask: It would be generally better if you kept the event handler as a private method, but made that call into a more appropriately-named method - which was *also* called externally. – Jon Skeet Dec 13 '11 at 17:43
3

You should make a public method in the first form that performs the logic you need.

Then, pass an instance of the first form to the second form and call the method on that instance.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I did it, now I have as public member of `form1.tabControl1_SelectedIndexChanged` in `form2`. and I can do: `parentForm.tabControl1_SelectedIndexChanged(??,null)` my question now is - it is possible to declare the tabControl1 control as public member? – The Mask Dec 13 '11 at 17:12
2

As Jon mentioned, you shouldn't make public... Here are some other samples that I've posted previously that explicitly walk through the creation of two forms and how to pass back-and-forth. Check these out

Community
  • 1
  • 1
DRapp
  • 47,638
  • 12
  • 72
  • 142