How to access user Control field in asp.net ?


UCProperty
Hi

If you are using asp.net user control in project then obviously you will get requirement to access that field in your parent page.

For example you are creating UserRegistration form as User control and going to use in so many module then you will create user control. Now you have to read all fields in your parent page then you can not read that field directly.

You can do like this

Step1: Create properties for field which one you are going to expose from your usercontrol like this.


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

public partial class UserReg : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string Name 
    {
        get { return txtName.Text; }
        set { txtName.Text = value; }
    }

    public string Address   
    {
        get { return txtAddress.Text; }
        set { txtAddress.Text = value; }
    }

    public string EmailId
    {
        get { return txtEmailId.Text; }
        set { txtEmailId.Text = value; }
    }


}

Step2: Now on button click i have to read that field then i can read like this

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

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
         
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string empName = EmpRegUserControl.Name;
        string empAddress = EmpRegUserControl.Address; 
        string emailId = EmpRegUserControl.EmailId;
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: