I have a UserControl inside a GridView. When are the Custom Event Handlers attached to the UserControl ? Please tell me because I have no idea.
In the scenario below the UserCreated event handler is null at the time the UserCreated event is fired, i.e. during DataBinding. Once the page has fully loaded the event handlers are available.
UserControl
public event EventHandler UserCreated;
public event EventHandler UserSelected;
///
/// Bubble up the UserCreated event
///
protected virtual void OnUserCreated(object sender, UserCreatedArgs e)
{
EventHandler handler = UserCreated;
/*
UserCreated above is null during databinding. No handler is present
A handler is present after page has fully loaded i.e. UserCreated != null
*/
if (handler != null)
{
handler(this, e);
}
}
///
/// Raise the OnDataBindingEvent
///
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
InitialiseControl();
}
///
/// Initialises the data in the UserControl.
///
private void InitialiseControl()
{
List userList =
UserController.GenerateUserNameDropDownList(UserGroupName);
OnUserCreated(userList);
}
Page On Which UserControl is Hosted
///
/// Handles the Load event of the Page control.
///
protected void Page_Load(object sender, EventArgs e)
{
UserCreatedHandler += UserControl.UserCreated
}
protected void UserCreatedHandler(object sender, UserControl.UserCreatedArgs e)
{
...handle userCreated event
}
Markup For The Page
asp:GridView ID="keyPersonnelGridView" runat="server" Columns asp:TemplateField ItemTemplate userControl:UserName ID="personnelList" runat="server" UserGroupName="All Users" /ItemTemplate /asp:TemplateField ..rest of tags closed /asp:GridView
Can any kind soul please explain why my Event handlers are not present when the event is fired ?