打印本文 打印本文 关闭窗口 关闭窗口
创建ASP.NET WEB自定义控件——例程2
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2621  更新时间:2009/4/23 10:43:49  文章录入:mintao  责任编辑:mintao

创建ASP.NET WEB自定义控件——例程2

作者:大毛

本文通过一段完整的代码向读者介绍复合自定义控件的制作,包括:自定义属性、事件处理、控件间数据传递等方面的技术。

作者在http://damao.0538.org有一些控件和代码,并在更新中,有兴趣的读者可以去下载。

以下是一个登陆框的代码,包括:用户名输入TextBox、密码输入TextBox、提交Button、重置Button以及承载以上四项的Panel。控件类名为LoginCtrl。

(例程使用C#)

using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.ComponentModel;

using System.Drawing;

 

namespace TestLib

{

     [DefaultProperty("BackColor"),

         ToolboxData("<{0}:LoginCtrl runat=server></{0}:LoginCtrl>")]

     public class LoginCtrl : System.Web.UI.WebControls.WebControl

     {

         private Color _fontColor = Color.Black;//声明字体颜色变量

         private Color _backColor = Color.White;//声明控件背景变量

首先声明要在复合控件中使用的子控件。

         private Label lblUserName = new Label();//显示“用户名”的Label控件

         private Label lblPassWord = new Label();//显示“密码”的Label控件

         private TextBox txtUserName = new TextBox();//用户名输入的TextBox控件

         private TextBox txtPassWord = new TextBox();//密码输入的TextBox控件

         private Button submitButton = new Button();//提交Button控件

         private Button clearButton = new Button();//重置Button控件

         private System.Web.UI.WebControls.Panel pnlFrame = new System.Web.UI.WebControls.Panel();//承载其它控件的容器Panel控件

当然要在符合控件中使用的事件一定要声明的,它们会出现在属性框的事件栏里。

         public event EventHandler SubmitOnClick;//声明自定义控件LoginCtrl的提交事件

         public event EventHandler ClearOnClick;//声明自定义控件LoginCtrl的重置事件

 

         public LoginCtrl()

         {

刚刚声明的子控件和事件要在这里进行初始化处理。

//初始化控件的属性

              this.lblUserName.Text = "用户名:";

              this.lblPassWord.Text = "密  码:";

              this.txtPassWord.TextMode = System.Web.UI.WebControls.TextBoxMode.Password;

 

              this.pnlFrame.Width = 240;

              this.pnlFrame.Height = 120;

              this.pnlFrame.BackColor = Color.Empty;

//添加提交按钮点击事件

              submitButton.Text = "确定";

              submitButton.Click += new EventHandler(this.SubmitBtn_Click);

//添加重置按钮点击事件

              clearButton.Text = "重置";

              clearButton.Click += new EventHandler(this.ClearBtn_Click);

//将声明的各子控件添加到LoginCtrl中

              this.Controls.Add(this.submitButton);

              this.Controls.Add(this.clearButton);

[1] [2] [3] [4] [5] [6]  下一页

打印本文 打印本文 关闭窗口 关闭窗口