CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Passing value from Page to UserControl in ASP.Net
Submitted By Satheesh Babu B
On 11/1/2008 8:07:27 AM
Tags: asp.net,C#,CodeDigest  

Most often, we will get requirements to pass values to user control form the codebehind class. This can be achieved by 2 ways,

 

  • Using Public Properties
  •  Using Page Item Collection

 

Using Public Properties

Declare a public property in user control and assign the value from codebehind/ASPX.

Refer the below code!

public partial class Header : System.Web.UI.UserControl

{

    private string _name;

 

    public string Name

    {

        get

        {

            return _name;

        }

        set

        {

            _name = value;

        }

    }

 

    protected void Page_Load(object sender, EventArgs e)

    {

        lblName.Text = Name;

    }

From ASPX

   <uc1:Header ID="Header1" Name="CodeDigest" runat="server" />

From CodeBehind

  protected void Page_Load(object sender, EventArgs e)

    {

       Header1.Name = "CodeDigest";

    }

 

Using Page Item Collection

There is new item collection packed with Page object from 2.0 framework. We can also use this collection to pass objects to usercontrols.

Note:

We can also use HttpContext object’s item collection for this.

 

Page CodeBehind

protected void Page_Load(object sender, EventArgs e)

    {      

        Page.Items.Add("Name", "CodeDigest");

    }

UserControl CodeBehind

public partial class Header : System.Web.UI.UserControl

{

   protected void Page_Load(object sender, EventArgs e)

    {

        lblName.Text = Page.Items["Name"].ToString();

    }

}

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..