jestges
jestges

Reputation: 3740

How to access usercontrol's values from page?

Hi I've created user control named test.ascs with one textbox. Now I added this user control in my default.aspx page. How can i access that textbox value from my default.aspx page?

is there any chance?

Upvotes: 6

Views: 21249

Answers (4)

dinesh S mehra
dinesh S mehra

Reputation: 21

How to access the value of a textbox from an USERCONTROL in a page which is using this usercontrol

step 1: in user control make an event handler

public event EventHandler evt;
    protected void Page_Load(object sender, EventArgs e)
    {
        txtTest.Text = "text123";
        evt(this, e);
    }

2: in page call the eventhandler

protected void Page_Load(object sender, EventArgs e)
    {
        userCntrl.evt += new EventHandler(userCntrl_evt);
    }

void userCntrl_evt(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)userCntrl.FindControl("txtTest");
        string s = txt.Text;
    }

Upvotes: 2

Paddy
Paddy

Reputation: 33867

If this is the purpose of the control, then create a public property on your user control that exposes this value, you can then access that from your page:

string textBoxValue = myUserControl.GetTheValue;

Upvotes: 3

BritishDeveloper
BritishDeveloper

Reputation: 13379

I usually expose the textbox's text property directly in test.ascx code behind like this:

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

Then you can get and set that textbox from the code behind of default.aspx like:

usrControl.Text = "something";
var text = usrControl.Text;

Upvotes: 7

KhanS
KhanS

Reputation: 1195

From your default page try to find the TextBox using your user control.

TextBox myTextBox = userControl.FindControl("YourTextBox") as TextBox;
string text = myTextBox.text;

Upvotes: 4

Related Questions