如何创建asp.net自定义Web控件事件处理程序

时间:2014-05-23 19:18:50

标签: c# asp.net event-handling custom-controls

我有一个OptionRadioButtonList类扩展RadioButtonList网页控件:

public class OptionRadioButtonList : RadioButtonList
{
    public EventHandler SelectionChangeEventHandler;
    public OptionRadioButtonList()
    {
        RepeatDirection = RepeatDirection.Vertical;
        AutoPostBack = true;
        Items.Add(new ListItem("YES", "YES"));
        Items.Add(new ListItem("NO", "NO"));
        CssClass = "rbList";
    }
    protected virtual void OnSelectionIndexChanged(object sender, EventArgs e)
    {
        if (SelectionChangeEventHandler != null)
        {
            SelectionChangeEventHandler(sender, e);
        }
    }
}

此类用于aspx.cs文件,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    // more code here
    OptionRadioButtonList rblist = new OptionRadioButtonList();
    rblist.SelectionChangeEventHandler += new EventHandler(mainQuestion_rblistHandler);
    LocalPlaceHolder.Controls.Add(rblist);   // this is a placeholder in aspx file
    // more code here
}
// RadioButtonList Event handler
protected void mainQuestion_rblistHandler(object sender, EventArgs e)
{
   RadioButtonList currentRblist = (RadioButtonList)sender;
   if (currentRblist.SelectedValue.Equals("YES"))
   {
      // do something
   } 
   else
   {
      // do something else      
   }
}

因此UI部分工作正常,但是当我更改是否radiobuttonList的选择时,Page_Load函数被调用,但是当我设置时,mainQuestion_rblistHandler无法访问那里有一个休息点。我不确定我做错了什么,任何人都可以帮助我。先感谢您。

1 个答案:

答案 0 :(得分:0)

您永远不会致电OnSelectionIndexChanged。覆盖基本OnSelectedIndexChanged方法并在其中调用OnSelectionIndexChanged

public class OptionRadioButtonList : RadioButtonList
{
    public EventHandler SelectionChangeEventHandler;
    public OptionRadioButtonList()
    {

        RepeatDirection = RepeatDirection.Vertical;
        AutoPostBack = true;
        Items.Add(new ListItem("YES", "YES"));
        Items.Add(new ListItem("NO", "NO"));
        CssClass = "rbList";
    }

    protected override void OnSelectedIndexChanged(EventArgs e)
    {
        var handler = SelectionChangeEventHandler;
        if (handler == null) return;
        handler(this, e);
    }
}