用戶控件(ASCX)向網頁(ASPX)傳值使用反射實現

用戶控件向網頁傳遞值,方法非常之多,此博文嘗試使用反射來實現。在站點中,建一個網頁以及一個用戶控件。 網頁切換至設計模式,拉用戶控件至網頁上。
Default.aspx,代碼如下:

<%@ 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,建一個帶兩個參數的public方法,代碼如下:

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;
}
}


接下來,我們創建一個用戶控件:

<%@ 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" />


寫用戶控件銨鈕事件,首先引用namespace using System.Reflection;
有關type.InvokeMember()方法,可以參考msdn:http://msdn.microsoft.com/zh-cn/library/de3dhzwy(v=vs.80).aspx

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 });
}
}


效果展示:
[img]http://dl2.iteye.com/upload/attachment/0120/6271/84457721-8f22-34fd-b824-70f92778fcde.png[/img]

原文網址:
http://www.jb51.net/article/34978.htm
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章