The enigma of software development.

How To: Communication between UserControls

Problem : Allow one UserControl(DepartmentSelectorControl) to communicate /pass a value to another UserControl which will in turn

 


using System;
using System.Linq;
using System.Web.UI.WebControls;

public partial class Controls_DepartmentSelectorControl : System.Web.UI.UserControl
{

	private string selecteddepartment = string.Empty;
	public string SelectedDepartment
	{
		get { return selecteddepartment; }
		set
		{
			selecteddepartment = value;
			selecteddepartment = uxDepartments.SelectedItem.Text;
		}
	}

	//Create eventhandler to be consumed by the host page
	public event EventHandler SelectDepartment;

	protected void Page_Load(object sender, EventArgs e)
	{
		using (var context = new AdventureWorksEntities())
		{

			var departments = context.Departments.Select(p => new Department
			{
				DepartmentID = p.DepartmentID,
				GroupName = p.GroupName,
				Name = p.Name,
				ModifiedDate = p.ModifiedDate
			});
			foreach (var department in departments)
			{
				var dItem = new ListItem { Text = department.Name, Value = department.DepartmentID.ToString() };
				uxDepartments.Items.Add(dItem);
			}

		}

	}

	protected void uxDepartments_SelectedIndexChanged(object sender, EventArgs e)
	{
		//Set the member variable to what the user has selected
		selecteddepartment = uxDepartments.SelectedItem.Text;
		if(SelectDepartment != null)
		{
			//Event is raised and corresponding eventhandler is called to respond to the event
			SelectDepartment(this, new EventArgs());
		}

	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">