How C # main form and subform manipulate each other's controls

Source: Internet
Author: User
Original address: Http://blog.csdn.net/knight94/archive/2006/03/18/628285.aspx

Many people fret about manipulating controls on a main form in a subform, or manipulating a control on a subform in a main form. In contrast, it's a little bit simpler to keep the subform object you created as soon as you create the subform in the main form.

The following focuses on the previous one, there are two common methods, basically similar:

The first is to define a static member in the main form class to hold the current main form object, for example:

public static Yourmainwindow Pcurrentwin = null;

Then, in the main form constructor, initialize the static member as follows:

Pcurrentwin = this;

Then invoke the parent form in the subform, which can be done with the main form class name. Pcurrentwin to manipulate the current main form.

The second is to define a private member in the subform to hold the current main form object, for example:

Private Yourmainwindow Pparentwin = null;

Then, in the subform constructor, add an argument, as follows:

Public Yourchildwindow (Yourmainwindow WinMain)

{

Pparentwin = WinMain;

Other code

}

When you create a subform on the main form, use this as a parameter to construct the subform so that the parent form is invoked in the subform, which can be done directly with "This.pparentwin".

But the above is just allowing you to access the current main form object, then how to manipulate the control, many people directly modify the control of the member accessor, that is, "private" to "public", I think this destroys the encapsulation of its own class, so I prefer the practice is to add public properties or methods to call For example:

public string ButtonText

{

get{return BTN. Text;}

set{btn. Text = value;}

}

Button_Click method in the public void Button_Click ()//main form

{

...

}


This.pParentWin.Button_Click (sender, E);//Call the main form in the subform Button_Click

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.