views:

260

answers:

4

I realize you can declaratively assign an event handler to a child control inside a formview by adding its attribute on the aspx page (i.e. onclick="Button_Click"), but if I wanted to do this programmatically, how would I go about it? That control isn't going to be found through FormView.FindControl in the Page's Init or Load events, so it can't be assigned in those stages. The DataBound event of the FormView will allow you to find the control, but is inappropriate, since that only happens once, and then the event won't always be bound, and it won't fire. I'm not asking because I can't get around it, I just wanted to know how it could be done.

Cheers.

+1  A: 

in c# this is accomplished via:
this.btnProcess.Click += new EventHandler(btnProcess_Click);

Christopher Kelly
I'm not talking about that line of code. I'm talking about where to put that line of code based on having to use FindControl to grab the control inside the FormView
Matt
+1  A: 

Have you tried PreRender? I think that is too late, but am surprised it wasn't in your post.

I find it strange you would add an event you expect to immediately fire. Why not just call the handler or function in that case.

Brad
+1  A: 

You should use the FormView's ItemCreated Event. It occurs after all rows are created, but before the FormView is bound to data.

Look at this MSDN page for more information

Gabriel McAdams
+1  A: 

Maybe I'm missing something! You can use event bubbling instead. But the FormView control does not have an event to handle the child controls' events. So, we've some changes.

[System.Web.UI.ToolboxData("<{0}:FormView runat=\"server\" />")]
public class FormView : System.Web.UI.WebControls.FormView
{

    private static readonly object _itemClickEvent = new object();

    [System.ComponentModel.Category("Action")]
    public event EventHandler<System.Web.UI.WebControls.FormViewCommandEventArgs> ItemClick
    {
        add { base.Events.AddHandler(_itemClickEvent, value); }
        remove { base.Events.RemoveHandler(_itemClickEvent, value); }
    }

    protected virtual void OnItemClick(System.Web.UI.WebControls.FormViewCommandEventArgs e)
    {
        EventHandler<System.Web.UI.WebControls.FormViewCommandEventArgs> handler = base.Events[_itemClickEvent] as EventHandler<System.Web.UI.WebControls.FormViewCommandEventArgs>;
        if (handler != null) handler(this, e);
    }

    protected override bool OnBubbleEvent(object source, EventArgs e)
    {
        this.OnItemClick((System.Web.UI.WebControls.FormViewCommandEventArgs)e);
        return base.OnBubbleEvent(source, e);
    }

}

The above code snippet demonstrated, how we can add an ItemClick event to the FormView control to handle the child controls' events. Now, you should map or drag the new FormView control instead.

Mehdi Golchin