Although there are already many. Net controls, Custom User Controls provide us with a broader development space. Reasonable Use of user controls can bring many benefits and convenience to our development.
However, there are some differences between a user control and a common page. Communication between a user control and a page and a user control may become a question that everyone must think about when using a user control. Of course, the original intention of the user control design should be a unit with relatively independent functions. A User Control completes a specific function, but in actual application, communication between such user controls is often required.
For example, we designed the file upload function as a user control. The user control defines all judgments, actions, and display information about the file format to be uploaded. When calling a page, we drag a page to define its properties. It is required that the uploaded files be displayed in a file list, which requires communication between the user control and the page.
The simplest method is to use session to save the value of the uploaded file, and then call the session directly on the page. Of course, this is not a problem, but it will cause you a headache to update and clear the session.
Of course, you can use the get method to pass page values, but this has more limitations. A control is used for more code, which is contrary to the starting point of the user control design.
We can solve this problem through reflection. The specific code example:
Call the user control on the page. After the user control function is complete, you need to update the home page.
Page npage = This. Parent. Page; // obtain the page object where the user control is located.
Type ptype = npage. GetType (); // obtain the object type
Methodinfo nmethod = ptype. getmethod ("binddata ");
// Call a method of this type. Only the method name is provided here. The specific method must be public with no return value.
Nmethod. Invoke (npage, null); triggers execution. In this way, the page is reloaded.
// Nmethod. Invoke (p, new object [] {"parameter 1", "parameter 2"}); if there is a parameter
To transfer values between controls, you can use the following methods:
Page npage = This. Parent. page;
Usercontrol UC = npage. findcontrol ("templetlist1") as usercontrol; // you only need to convert it to the user control type.
Type pagetype = UC. GetType ();
Methodinfo nmethod = pagetype. getmethod ("binddata ");
Nmethod. Invoke (UC, null );