这是一个选择省份然后将点击事件上传到控件顶层在页面处理事件的一个例子。加粗部分是整个上传事件过程。上传事件(暴露事件)、暴露属性、复杂属性管理、样式管理等是asp.net服务器自定义控件的高级主题。
using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Yeno.EnBiz.News.Tools;
namespace Yeno.EnBiz.News.Controls
{
/// <summary>
/// ResearchCtrl 的摘要说明。
/// </summary>
[ToolboxData("<{0}:LocalCtrl_Province runat=server></{0}:LocalCtrl_Province>")]
public class LocalCtrl_Province : System.Web.UI.WebControls.WebControl,INamingContainer
{
private TableCell _Province;
public event CommandEventHandler ClickProvince;
/// <summary>
/// 将此控件呈现给指定的输出参数。
/// </summary>
/// <param name="output"> 要写出到的 HTML 编写器 </param>
protected override void Render(HtmlTextWriter writer)
{
AddAttributesToRender(writer);
writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding,"5",false);
writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing,"0",false);
writer.AddAttribute(HtmlTextWriterAttribute.Width,"100%",false);
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);
_Province.RenderControl(writer);
writer.RenderEndTag();
writer.RenderEndTag();
}
protected override void CreateChildControls()
{
if(!Page.IsPostBack)
{
Controls.Clear();
ClearChildViewState();
}
_Province=new TableCell();
CreateProvince();
this.Controls.Add(_Province);
}
protected void CreateProvince()
{
DataTable dtb=(DataTable)DataCall.RunSqlSP("N_Province_GetAll",ReturnType.ExecuteReader);
for(int i=0;i<dtb.Rows.Count;i++)
{
LinkButton lb=new LinkButton();
lb.Text=dtb.Rows[i]["PROVINCE"].ToString().Trim();
lb.CausesValidation=false;
lb.CommandArgument=dtb.Rows[i]["ID"].ToString();
lb.Command +=new CommandEventHandler(Province_Command);
_Province.Controls.Add(lb);
_Province.Controls.Add(new LiteralControl(" "));
}
dtb.Dispose();
}
protected void Province_Command(Object sender,CommandEventArgs e)
{
OnClickProvince(e);
}
protected void OnClickProvince(CommandEventArgs e)
{
if(ClickProvince!=null)
{
ClickProvince(this,e);
}
}
}
}