.net 下动态加载自定义控件后传值及函数调用方法
自定义的用户控件,可通过在页面中直接引入及动态加载使用:
1.直接在页面aspx文件中引用的,可直接在其.cs文件中通过控件ID调用其公共属性及方法:
eg:
自定义控件ITyouhuiCtl:
ITyouhuiCtl.ascx.cs:
定义属性:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | private string url; public string Url { get { return url; } set { url = value; } } public string SetUrl( string urlInput, string para2) //通过函数调用来设置多个变量 { url = urlInput; … } |
页面Default.aspx:
2 3 4 | <%@ 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:
2 3 4 5 6 7 8 9 | 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中即可直接使用:
2 3 4 5 6 7 | 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述