tags:

views:

494

answers:

2

Hello,

I am creating a dynamic button in a custom class, outside of the .aspx codebehind. The custom class creates a Table object and generates a column of Buttons within that table. Once generated, the Table is loaded into a placeholder control. Everything is functioning well except for this problem:

How do I programmatically assign a Button Object a 'Click' event within the custom class?

 MyButton.Click += new EventHandler(MyButtonClick);

This results in: 'The name 'MyButtonClick' does not exist in the current context' error.

I know it doesn't exist in the current context, but once the aspx page is rendered, the codebehind will include a method to handle 'MyButtonClick'. I don't know how store a Click event method name into a Button object from a custom class and pass it off to the aspx codebehind to be rendered.

+4  A: 

You have to define an event in your custom control. Fire that event on button click so that your .aspx can handle it.

EDIT: Same principles apply to a custom class.

Control Code-Behind:

public delegate void ButtonEventHandler();
public event ButtonEventHandler ButtonEvent;

protected void Button1_Click(object sender, EventArgs e)
{
    ButtonEvent();
}

.ASPX Code Behind:

protected override void OnInit(System.EventArgs e)
{               
     control1.ButtonEvent+= 
              new Control1.ButtonEventHandler (whatever_ButtonEvent);

}

protected void whatever_ButtonEvent()
{
    //do something
}
rick schott
A: 

Let's take this concept and apply it to a user control that has a textbox and two buttons. The user control is placed within a Gridview. When my code runs the method in my event handler method is always null. I think has to do w/the fact the a button is is in a user control which is in the gridview.

Here is my user control code.

public partial class User_Controls_GridViewFilter : System.Web.UI.UserControl {

public event EventHandler UserControlButtonClicked;

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        renderPage();
    }
}



private void OnUserControlButtonClick()
{
    if (UserControlButtonClicked != null)
    {
        UserControlButtonClicked(); 
    }
}

protected void btnSearch_Click(object sender, EventArgs e)
{
    OnUserControlButtonClick();
}

protected void btnReset_Click(object sender, EventArgs e)
{
    OnUserControlButtonClick();
}

}

I register the control on the aspx page.

        ((User_Controls_GridViewFilter)gvMapLayer.HeaderRow.FindControl("FilterBox1")).UserControlButtonClicked
          += new ButtonEventHandler(User_Controls_GridViewFilter_UserControlButtonClicked);
Bruce