Click here to Skip to main content
6,293,171 members and growing! (11,750 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto License: The Code Project Open License (CPOL)

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

By Fazlur Rahman

A tutorial which describes how to access a user control from another one using event handler
XML, C# 2.0, ASP.NET
Posted:25 Sep 2008
Views:4,360
Bookmarked:10 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
5 votes for this article.
Popularity: 2.10 Rating: 3.00 out of 5
2 votes, 40.0%
1

2

3
2 votes, 40.0%
4
1 vote, 20.0%
5
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


Member
I am Bachelor in CSE from KUET,Bangladesh. I have more than 3 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.


Occupation: Software Developer (Senior)
Company: TalentPlus Software Inc.
Location: Bangladesh Bangladesh

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralMy vote of 1 Pinmemberhayk10:07 25 Jan '09  
Generalthanks PinmemberOleg Shilovskiy9:23 3 Oct '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 25 Sep 2008
Editor: Deeksha Shenoy
Copyright 2008 by Fazlur Rahman
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project