如果一个服务器控件需要支持回传事件,那么它必须要实现IPostBackEventHandler接口
需要实现RaisePostBackEvent(string eventArgument)方法
控件代码
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace kjlx.BLL.IPostBack
{
[ParseChildren(true), //解析为属性
DefaultEvent("Click")]
public class IPostBackTest2 : WebControl, IPostBackEventHandler
{
//外层DIV
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.Div; }
}
/// <summary>
/// 给Div添加属性和样式
/// </summary>
/// <param name="writer"></param>
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer); //由于AddAttributeToRender()方法实现了对控件基本属性和样式的支持,所以就算需要重写这个方法,也应当调用base.AddAttributeToRender(),以使自定义控件获得基本的功能。
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "120px");
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "35px");
writer.AddStyleAttribute(HtmlTextWriterStyle.BackgroundColor, "#0000aa");
writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");
//如果是链接,回传事件放在href中,使用GetPostBackClientHyperlink string upRef = Page.ClientScript.GetPostBackEventReference(this, null); //创建onclick事件
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, upRef); //给onclick事件赋值 } //Click事件属性 static object ClickHandler=new object(); [Category("Action")] public event EventHandler Click { add { Events.AddHandler(ClickHandler,value); } remove { Events.RemoveHandler(ClickHandler,value); } } /// <summary> /// 处理网页回传事件 /// 触发控件相应的事件 /// </summary> /// <param name="eventArgument"></param> public void RaisePostBackEvent(string eventArgument) { EventArgs args=new EventArgs(); if (Events[ClickHandler] != null) { (Events[ClickHandler] as EventHandler)(null, args); } } }}
html代码
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<cc1:IPostBackTest2 ID="IPostBackTest1" runat="server"
onclick="IPostBackTest1_Click" />
后台代码
protected void IPostBackTest1_Click(object sender, EventArgs e)
{
Label1.Text = "111";
}
显示结果