There are many methods to pass user controls to web pages. This blog post attempts to use reflection for implementation. Create a webpage and a user control on the site. Switch the webpage to the design mode and pull the user control to the webpage.
Default. aspx:Copy codeThe Code is as follows: <% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>
<% @ Register Src = "InsusUC. ascx" TagName = "InsusUC" TagPrefix = "uc1" %>
<! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Uc1: InsusUC ID = "InsusUC1" runat = "server"/>
<Br/>
<Br/>
Hi, You input infor as below: <br/>
First textbox value:
<Asp: Label ID = "LabelshowFirstValue" runat = "server" Text = "" ForeColor = "Red"> </asp: Label> <br/>
Second textbox value:
<Asp: Label ID = "LabelshowLastValue" runat = "server" Text = "" ForeColor = "Red"> </asp: Label>
</Div>
</Form>
</Body>
</Html>
Default. aspx. cs: create a public method with two parameters.Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
}
Public void ReadUCMessage (string value1, string value2)
{
This. LabelshowFirstValue. Text = value1;
This. LabelshowLastValue. Text = value2;
}
}
Next, we will create a user control:Copy codeThe Code is as follows: <% @ Control Language = "C #" AutoEventWireup = "true" CodeFile = "InsusUC. ascx. cs" Inherits = "InsusUC" %>
First Name <asp: TextBox ID = "TextboxFirstName" runat = "server"> </asp: TextBox> <br/>
Last Name <asp: TextBox ID = "TextboxLastName" runat = "server"> </asp: TextBox> <br/>
<Asp: Button ID = "ButtonTransmit" runat = "server" Text = "Transmit" OnClick = "ButtonTransmit_Click"/>
Write the button event, first reference namespace using System. Reflection;
For the type. InvokeMember () method, see msdn: http://msdn.microsoft.com/zh-cn/library/de3dhzwy (v = vs.80). aspxCopy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Reflection;
Public partial class InsusUC: System. Web. UI. UserControl
{
Protected void Page_Load (object sender, EventArgs e)
{
}
Protected void ButtonTransmit_Click (object sender, EventArgs e)
{
String v1 = this. TextboxFirstName. Text. Trim ();
String v2 = this. TextboxLastName. Text. Trim ();
This. Page. GetType (). InvokeMember ("ReadUCMessage", BindingFlags. InvokeMethod, null, this. Page, new object [] {v1, v2 });
}
}
Demo: