博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
动态添加用户控件
阅读量:7079 次
发布时间:2019-06-28

本文共 1695 字,大约阅读时间需要 5 分钟。

本篇教你动态添加用户控件。

 

为了让用户控件能ASP.NET页面实现动态添加,首先写一个接口IGetUCable,这个接口有一个函数,返回对象类型是UserControl。

ExpandedBlockStart.gif
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
///
 
<summary>
///
 Summary description for IGetUCable
///
 
</summary>
namespace Insus.NET
{
    
public 
interface IGetUCable
    {
        UserControl GetUC();    
    }
}

有了接口之后,需要创建用户控件Calculator.ascx: 

ExpandedBlockStart.gif
View Code
<%
@ Control Language
=
"
C#
"
 AutoEventWireup
=
"
true
"
 CodeFile
=
"
Calculator.ascx.cs
"
 Inherits
=
"
Calculator
"
 
%>
Number A: 
<
asp:TextBox 
ID
="TextBox1"
 runat
="server"
></
asp:TextBox
> 
<
br 
/>
<
br 
/>
Number B: 
<
asp:TextBox 
ID
="TextBox2"
 runat
="server"
></
asp:TextBox
><
br 
/>
<
asp:Button 
ID
="ButtonEqual"
 runat
="server"
 Text
="="
 
    OnClick
="ButtonEqual_Click1"
 
/>
<
br 
/>
Result: 
<
asp:Label 
ID
="LabelResult"
 runat
="server"
 Text
=""
></
asp:Label
>

  

 Calculator.ascx.cs,cs实现接口:

ExpandedBlockStart.gif
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Insus.NET;
public 
partial 
class Calculator : System.Web.UI.UserControl,IGetUCable 
{       
    
protected 
void Page_Load(
object sender, EventArgs e)
    {
    }
    
protected 
void ButtonEqual_Click1(
object sender, EventArgs e)
    {
        
decimal a = 
decimal.Parse(
this.TextBox1.Text.Trim());
        
decimal b = 
decimal.Parse(
this.TextBox2.Text.Trim());
        
this.LabelResult.Text = (a + b).ToString ();
    }
    
public UserControl GetUC()
    {
        
return 
this;
    }  
}

 

 最后是在需要加载用户控件的aspx的Page_load事件写:

ExpandedBlockStart.gif
View Code
 
protected 
void Page_Load(
object sender, EventArgs e)
    {
        IGetUCable uc1 = (IGetUCable)LoadControl(
"
~/Calculator.ascx
");
        
this.form1.Controls.Add(uc1.GetUC());
    }

 

 用户控件加载之后运行效果:

 

源程序(.NET3.5 + ASP.NET + C#)

 

 

 

转载地址:http://buvml.baihongyu.com/

你可能感兴趣的文章
为什么 NSLog 不支持 Swift 对象
查看>>
如何优雅的选择字体(font-family)
查看>>
为 Koa 框架封装 webpack-dev-middleware 中间件
查看>>
深入浅出JavaScript:理解函数
查看>>
将群晖 NAS 安全地暴露到公网中
查看>>
【二次元的CSS】—— 用 DIV + CSS3 画咸蛋超人(详解步骤)
查看>>
Android程序逆向分析
查看>>
在阿里云centOS环境下搭建基于thinkphp的网站
查看>>
RegEx 快速掌握最基本的正则语法
查看>>
过去的2015年
查看>>
Webpack + React 开发之路
查看>>
【译】使用 AngularJS 和 Electron 构建桌面应用
查看>>
【经验总结】记一次艰难的居中--日历榜单
查看>>
所有博客将会誊到http://www.xumenger.com/
查看>>
Jodd 5.0.8 发布,Java 常用工具包
查看>>
某网页数据爬取记录
查看>>
GoLand 2019.1 Beta 发布,重要里程碑
查看>>
浅谈SAP Cloud for Sales 自动化
查看>>
舍弗勒为自动驾驶做出准备,L4/L5级智能转向与线控技术 | 2019上海车展 ...
查看>>
阿里云文件存储NAS跨VPC挂载
查看>>