Click here to Skip to main content
Click here to Skip to main content

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

By , 25 Sep 2008
Rate this:
Please Sign up or sign in to vote.
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:

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.

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:

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:

<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:

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)

About the Author

Fazlur Rahman
Software Developer (Senior) MediaNet Group
United Arab Emirates United Arab Emirates
I am Bachelor in CSE from KUET,Bangladesh. I have more than 6 years experience in ASP.NET and C# and currently working in a software company in Dubai,UAE as a Senior 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

 
QuestionUC postback PinmemberMember 429614719-Dec-13 17:52 
GeneralNice article PinmemberBert ONeill11-Apr-12 21:59 
Questiona different approach PinmemberMember 861010431-Jan-12 5:57 
AnswerUC to UC Pinmemberrahul17_1823-Jan-13 0:56 
GeneralMy vote of 1 Pinmemberhayk25-Jan-09 9:07 
Generalthanks PinmemberOleg Shilovskiy3-Oct-08 8:23 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 25 Sep 2008
Article Copyright 2008 by Fazlur Rahman
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid