Dailycode.info

Short solution for short problems

Create a custom event handler for an ASP.net user control with custom event arguments.

Just a quick tutorial on how to pass events from a user controls to the page.

Imagine you have a user control that has some drop down lists filled. When the dropdown list selection changes, you want to pass this event to the page that is implementing the user control.

First lets create our own general event handler using our own event arguments (This class can be in a general class, so you can reuse it):

/// <summary>

/// Summary description for Project Drop Down

/// </summary>

public class PDDCommandEventArgs

{

    private string _id;

    public string ID

    {

        get { return _id; }

    }

 

    private string _description;

    public string Description

    {

        get { return _description; }

    }

    public PDDCommandEventArgs(string guid, string description)

    {

        _id = guid;

        _description = description;

    }

}

 

public delegate void PDDCommandEventHandler(object sender, PDDCommandEventArgs e);

 

Next , we declare the event handler on our user control:

public event PDDCommandEventHandler ValueChanged;

 

Then we fire the event when the dropdown is selected on the user control:

private void OnValueChanged(object sender, PDDCommandEventArgs e)

{

    if (ValueChanged != null) ValueChanged(this, e);

}

 

protected void drpSteps_SelectedIndexChanged(object sender, EventArgs e)

{

    OnValueChanged(this, new PDDCommandEventArgs(this.drpSteps.SelectedValue, this.drpSteps.SelectedItem.Text));

}

 

Once a page that uses this control has declared the event handler, it will be fired when the selection changes:

projectDropDown1.StepChanged += new ZinqProjectsWeb.Controls.PDDCommandEventHandler(projectDropDown1_StepChanged);

void projectDropDown1_StepChanged(object sender, Controls.PDDCommandEventArgs e)

{

    taskDetailsControl.FillDefaults(int.Parse(e.ID));

}