1

enter image description here

I am converting a Delphi 7.0 application to .Net(2.0).

In Delphi application there is similar implementation like "User Control", So I too did same in my C# application.

But in Delphi it is possible to code UserControl's events implemantations on main(parent), unlikely in .Net it is a must(not sure) to do it at UserControl level.

My Questions are,

  1. Can't we do same in .Net?
  2. Altenative method(direct) method of doing that

Note: I have achived what I want through delegates/events, But I prefer the way done it in Delphi

RRUZ
  • 134,889
  • 20
  • 356
  • 483
Buddhi Dananjaya
  • 643
  • 2
  • 12
  • 32
  • Can you show some Delphi code? It's been a while since I programmed in Delphi but I don't recall being able ot do what you're saying. The implementation of a event belongs in the class not in some other class. So if you show us some Delphi code and explain what you're trying to do, it'll be easier to show you how you should do it in .NET – Shiv Kumar Feb 10 '11 at 06:13
  • I wonder how I show code... Buecase it is not about coding, it is something about way of coding.... simply it is ... How to implement an event(fucntion) for control on a usercontorl, on the form which it resides(parent) ? – Buddhi Dananjaya Feb 10 '11 at 06:17
  • Yes,you can do it in .net.create a delegate/event in usercontrol and register that event in main form. – santosh singh Feb 10 '11 at 06:24
  • @santosh - Please see my note. – Buddhi Dananjaya Feb 10 '11 at 06:29

1 Answers1

1

You can couple of alternate ways to achieve this:

  1. Make controls members (generated by designer) within user controls as public or internal (possible by setting Modifiers property in control properties). Then you can write code such as UserCtr1.UserCtr2.UserCtrl3.Btn1 to reference the button and attach event handler to it within form code. I won't prefer this approach because it breaks the encapsulation. But if your taking view that user controls are just a UI template (w/o any behavior) then it may work out for you.
  2. Yet another way would be to have local event handlers within control code but make them invoke corresponding methods from Form. This can be accomplished by using TopLevelControl property. For example, in User Ctrl 3 code

    private void Btn1_Click(object sender, EventArgs e) { ((FormMain)this.TopLevelControl).Search(param1); }

Problem with this approach is tight coupling with form and way to resolve would be to inject some interface to invoke functions from user control. Form can implement the interface. The instance (of interface) can be injected to all user controls via some kind of IoC Container/DI framework.

VinayC
  • 47,395
  • 5
  • 59
  • 72