处理click事件自定义服务器控件

时间:2013-05-15 11:18:48

标签: asp.net postback custom-server-controls buttonclick

我可以使用imagebutton控制:

    ... 
    ImageButton btn;

    public MyControl()
    {
        btn = new ImageButton();      
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Page.RegisterRequiresPostBack(this);
    }

    protected override void CreateChildControls()
    {

        btn.Height = Height;
        btn.Width = Height;

        btn.Click += new System.Web.UI.ImageClickEventHandler(RaiseLeftClickEvent);
    }

    private void RaiseLeftClickEvent(object sender, ImageClickEventArgs e)
    {
        throw new NotImplementedException();
    }

当我点击按钮时,Click事件不会触发。

1 个答案:

答案 0 :(得分:2)

我认为你必须在OnInit范围内创建点击事件..

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    Page.RegisterRequiresPostBack(this);
    base.CreateChildControls();
    btn.Click += new System.Web.UI.ImageClickEventHandler(RaiseLeftClickEvent);
}

更新

首先,控件的基类必须是WebControl类。

OnInit范围定义按钮的事件:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    Page.RegisterRequiresControlState(this);
    Controls.Clear();

    base.CreateChildControls();
    btn.Click += btnImageButton_Click;
    Controls.Add(btn);

}


void btnImageButton_Click(object sender, EventArgs e)
{
    //Handle Click event.. 
}

希望这会有所帮助..