Click here to Skip to main content
15,881,248 members
Articles / Web Development / ASP.NET
Article

How To Access a User Control from Another User Control in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.80/5 (12 votes)
25 Sep 2008CPOL2 min read 71.1K   1.3K   21   7
A tutorial which describes how to access a user control from another one using event handler
EventDrivenUC

Introduction

Sometimes it is required to access a user control from another user control that resides on the same page in ASP.NET. This purpose can be achieved in several ways. Here I have two controls. One is an editor and the other one is a list. My target is to create a communication between these two controls. This article describes the way to achieve this goal.

Possible Ways

The possible ways to access a user control from another user control are:

This article highlights the second one.

Basic Methodology

The communication between the controls takes place via the container page. One control triggers an event which is caught by the page and then the page accesses the other control using public methods or properties of that. Here the editor control triggers the save event and the list control triggers the edit event. These are then caught by the page and necessary steps are taken. So the sequence of events is as follows:

  • Editor triggers save event to refresh the list control. 
  • List triggers edit event to view the record on the editor. 

So there are two events and respective event arguments here:

C#
public class PersonEventArgs:EventArgs
{
    private bool isSuccess = false;
    public bool IsSuccess
    {
        get { return isSuccess; }
        set { isSuccess = value; }
    }
    public PersonEventArgs(bool success)
	{
        isSuccess = success;
	}
}
public class EditPersonEventArgs:EventArgs
{
    private int personId = 0;
    public int PersonId
    {
        get { return personId; }
        set { personId = value; }
    }
    public EditPersonEventArgs(int Id)
    {
        personId = Id;
    }
}

Editor Control

PersonEditor.ascx has the SavedPerson event which is triggered when clicked on save button. Default.aspx page catches the event and calls LoadPersonList() method of PersonList.ascx.

C#
public partial class PersonEditor : System.Web.UI.UserControl
{
    public delegate void SavePerson(object sender, PersonEventArgs arg);
    public event SavePerson SavedPerson;
    protected void btnSave_Click(object sender, EventArgs e)
    {
        Person newPerson = new Person();
        newPerson.Age = Convert.ToInt32(txtAge.Text);
        newPerson.ContactNo = txtContactNo.Text;
        newPerson.Email = txtEmail.Text;
        newPerson.FatherName = txtFatherName.Text;
        newPerson.Id = Convert.ToInt32(hfPersonId.Value);
        newPerson.Name = txtName.Text;
        PersonDataAccess newDA = new PersonDataAccess();
        bool status=newDA.Save(newPerson);
        if (SavedPerson != null)
        {
            PersonEventArgs newArg = new PersonEventArgs(status);
            SavedPerson(this, newArg);
        }
        if (status)
        {
            ClearForm();
        }
    }
    public void PrepareEditView(int personId)
    {
        PersonDataAccess newDA = new PersonDataAccess();
        Person currentPerson = newDA.GetPersonById(personId);
        if (currentPerson != null)
        {
            txtAge.Text = currentPerson.Age.ToString();
            txtContactNo.Text = currentPerson.ContactNo;
            txtEmail.Text = currentPerson.Email;
            txtFatherName.Text = currentPerson.FatherName;
            txtName.Text = currentPerson.Name;
            hfPersonId.Value = personId.ToString();
        }
    }

    private void ClearForm()
    {
        txtAge.Text = string.Empty;
        txtContactNo.Text = string.Empty;
        txtEmail.Text = string.Empty;
        txtFatherName.Text = string.Empty;
        txtName.Text = string.Empty;
        hfPersonId.Value = "0";
    }
}	 

List Control

PersonList.ascx control has the EditedPerson event which is triggered when you click on the edit link of GridView. Here, it needs to pass the person's id whose record is going to be edited. This id is passed by EditPersonEventArgs:

C#
public partial class PersonList : System.Web.UI.UserControl
{
    public delegate void EditPerson(object sender, EditPersonEventArgs arg);
    public event EditPerson EditedPerson;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadPersonList();
        }
    }
    public void LoadPersonList()
    {
        PersonDataAccess newDA = new PersonDataAccess();
        grdViewPersonList.DataSource = newDA.GetPersonList();
        grdViewPersonList.DataBind();
    }
    protected void grdViewPersonList_RowEditing(object sender, GridViewEditEventArgs e)
    {
        if (EditedPerson != null)
        {
            int personId = Convert.ToInt32
			(grdViewPersonList.DataKeys[e.NewEditIndex].Value);
            EditPersonEventArgs newArg = new EditPersonEventArgs(personId);
            EditedPerson(this, newArg);
        }
    }
    protected void grdViewPersonList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int personId = Convert.ToInt32(grdViewPersonList.DataKeys[e.RowIndex].Value);
        PersonDataAccess newDA = new PersonDataAccess();
        bool status = newDA.Delete(personId);
        if (status)
        {
            LoadPersonList();
        }
    }
}	 

Control Container

At last, put the controls on the Default.aspx page and set the event handlers ucntrlPersonEditor_SavedPerson and ucntrlPersonList_EditedPerson to the controls OnSavedPerson and OnEditedPerson events like:

XML
<body>
    <form id="form1" runat="server">
        <div>
            <strong>User Control 1</strong><br />
            <div style="border-style:solid; border-width:1px; 
			border-color:Black; clear:both; width:510px;">
                <uc1:PersonEditor runat="server" ID="ucntrlPersonEditor" 
				OnSavedPerson="ucntrlPersonEditor_SavedPerson" />
            </div>
            <br />
            <strong>User Control 2</strong><br />
            <div style="border-style:solid; border-width:1px; 
			border-color:Black; clear:both; width:510px;">
                <uc1:PersonList runat="server" 
		ID="ucntrlPersonList" OnEditedPerson="ucntrlPersonList_EditedPerson"/>
            </div>
        </div>
    </form>
</body>

And the event handlers code looks like this:

C#
public partial class _Default : System.Web.UI.Page 
{
    protected void ucntrlPersonEditor_SavedPerson(object sender, PersonEventArgs e)
    {
        if (e.IsSuccess)
        {
            ucntrlPersonList.LoadPersonList();
        }
    }
    protected void ucntrlPersonList_EditedPerson(object sender, EditPersonEventArgs e)
    {
        if (e.PersonId>0)
        {
            ucntrlPersonEditor.PrepareEditView(e.PersonId);
        }
    }
}	 

Points of Interest

The functionality includes:

  • The editor input values are saved in an XML file when clicked on the save button and then an event is triggered and passed to the container page. The page calls a method of the list control to reload the gridview.
  • Any record in the list can be viewed and updated by clicking on the edit link. It triggers and passes an event with a parameter id to the page which then calls a method to view the record on the editor.

History

  • 26th September, 2008: Initial post 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Ominto Inc
United Arab Emirates United Arab Emirates
I am Bachelor in CSE from Khulna University of Engineering & Technology,Bangladesh. I have more than 11 years experience in software design & development, data analysis & modeling, project management and currently working in a software company in Dubai,UAE as a Lead Software Engineer. I am MCAD(Microsoft Certified Application Developer) certified since 2005. Please feel free to contact with me at nill_akash_7@yahoo.com.


Comments and Discussions

 
Questioni am getting errors as underlined words while executing the code,i stucked here, help me to know this Pin
VeenGreen21-Jul-16 8:33
VeenGreen21-Jul-16 8:33 
QuestionUC postback Pin
Member 429614719-Dec-13 17:52
Member 429614719-Dec-13 17:52 
GeneralNice article Pin
Bert ONeill11-Apr-12 21:59
Bert ONeill11-Apr-12 21:59 
Questiona different approach Pin
Member 861010431-Jan-12 5:57
Member 861010431-Jan-12 5:57 
AnswerUC to UC Pin
rahul17_1823-Jan-13 0:56
professionalrahul17_1823-Jan-13 0:56 
GeneralMy vote of 1 Pin
hayk25-Jan-09 9:07
hayk25-Jan-09 9:07 
Generalthanks Pin
Oleg Shilovskiy3-Oct-08 8:23
Oleg Shilovskiy3-Oct-08 8:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.