.net 下动态加载自定义控件后传值及函数调用方法

自定义的用户控件,可通过在页面中直接引入及动态加载使用:

1.直接在页面aspx文件中引用的,可直接在其.cs文件中通过控件ID调用其公共属性及方法:

eg:

自定义控件ITyouhuiCtl:

ITyouhuiCtl.ascx.cs:

定义属性:

private string url;

public string Url 
{ 
    get { return url; } 
    set { url = value; } 
}

public string SetUrl(string urlInput,string para2)//通过函数调用来设置多个变量

{

   url = urlInput;

…

}

页面Default.aspx:

<%@ Register Src="/Controls/ITyouhuiCtl.ascx" TagName="ITyouhuiCtl" TagPrefix="WFO" %>

<WFO:ITyouhuiCtlID="yh" runat="server" />

Default.aspx.cs:

yh.Url = “http://www.ityouhui.com”;//直接引用

2.动态加载自定义控件引入的,函数调用方法:

对于函数调用:

eg:

Default.aspx:

<asp:Panel ID="extPL1" runat="server" Visible ="false" />

Daefault.aspx.cs:

Control c = Page.LoadControl(Request.ApplicationPath + "/Controls/ITyouhuiCtl.ascx");//动态加载控件 
Type tc = c.GetType(); 
System.Reflection.MethodInfo m = tc.GetMethod("SetUrl"); //xx为控件中函数 
object[] bjParas = new object[2]; 
bjParas[0] = “http://www.ityouhui.com/channel/notebook”;//控件中函数参数 
bjParas[1] = "seller"; 
m.Invoke(c, bjParas);//调用 
extPL1.Controls.Add(c);//将控件添加到面板占位处

3.动态加载自定义控件,调用属性:

首先需要在自定义控件中申明类名:

eg:

自定义控件ITyouhuiCtl需添加ClassName属性:

ITyouhuiCtl.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ITyouhuiCtl.ascx.cs" ClassName="ITyouhuiCtl" Inherits="Controls_ITyouhuiCtl" %>

在引用页Default.aspx中注册:

<%@ Register src="/Controls/ITyouhuiCtl.ascx" tagname="ITyouhuiCtl" tagprefix="WFO" %>

在Default.aspx.cs中即可直接使用:

ASP.ITyouhuiCtl c; 
c = (ASP.ITyouhuiCtl)(Page.LoadControl(Request.ApplicationPath + "/Controls/ITyouhuiCtl.ascx")); 
extPL1.Controls.Add(c); 
c.Url = “http://www.ityouhui.com/channel/camera”;//直接调用!

//同样,这里可以调用函数,更为简单

注:ITyouhuiCtl 前一般是ASP.的名字空间,当然各人配置不一样可能有差异,不知道的情况下,可在前面几步完成之后,调用处直接输入控件名ITyouhuiCtl ,将鼠标移上去,vs会提示添加名字空间,加上即可;

OVER!

ORG:http://blog.donews.com/me1105/archive/2011/05/15/154.aspx

原文地址:https://www.cnblogs.com/me115/p/2046873.html