Thursday, January 1, 2009

Passing an Event to the Parent Control by Using Delegates

For the purpose implementation of inner control should implement event handler, custom argument class and delegate. Custom argument class is used to pass inner control specific values to the container control.

using System.Web.UI.WebControls;

namespace InteractiveControls{
// Interactive Control
public class MyInteractiveControl : CompositeControl
{
/// <summary>
/// Event for delegate method
/// </summary>
public event ShowClickEventHandler ShowClicked;

/// <summary>
/// Button control
/// </summary>
private Button btnShow;

/// <summary>
/// CreateChildControls is responsible for creating the controls to form this composite control
/// </summary>
protected override void CreateChildControls()
{
this.btnShow = new
Button();
this.btnShow.Text = "Show";
this.btnShow.Click += new
EventHandler(btnShow_Click);
this.Controls.Add(btnShow);
}

private void btnShow_Click(object sender, EventArgs e)
{
OnShowClick(new ShowClickEventArgs(25, 100));
}
void OnShowClick(ShowClickEventArgs e)
{
ShowClicked(this, e);
}
}

/// <summary>
/// Delegate method for Show button clicked event handler
/// </summary>
public delegate void ShowClickEventHandler(object sender, ShowClickEventArgs e);
/// <summary>
/// Event argument class for ShowClickEventArgs
/// </summary>
public class ShowClickEventArgs : EventArgs
{
private int m_From;
private int m_To;
public ShowClickEventArgs(int from, int to)
{
this.m_From = from;
this.m_To = to;
}
public int From
{
get { return m_From; }
}
public int To
{
get { return m_To; }
}
}
}

'MyInteractiveControl_ShowClicked' method in the container control will be invoked in 'Show' button click, which is residing in the inner control. By implementing custom argument class appropriately, can access values in the interactive control from container control.

namespace ContainerControls
{
// Container Control
public class MyInteractiveControl : CompositeControl
{
protected override void CreateChildControls()
{
MyInteractiveControl ctrl = new MyInteractiveControl();
ctrl.ShowClicked += new ShowClickEventHandler(MyInteractiveControl_ShowClicked);
this.Controls.Add(ctrl);
}

/// <summary>
/// Event fires when the Show button clicked
/// </summary>
private void MyInteractiveControl_ShowClicked(object sender, ShowClickEventArgs e)
{
Controls.Add(new
LiteralControl(string.Concat("From:", e.From.ToString(), " - To:", e.To.ToString())));
}
}
}

More about delegates.....

No comments: