Assign Event Programmatically to Child Inside FormView
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 cou开发者_JAVA技巧ld be done.
Cheers.
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
in c# this is accomplished via:
this.btnProcess.Click += new EventHandler(btnProcess_Click);
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.
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.
精彩评论