Set value of TextBox in UserControl from hosting web form

  • Thread starter Thread starter Robbie
  • Start date Start date
R

Robbie

I have a Web Form with some tailored logos and artwork. The web form
also has a user control that has typical registration info on it
(Name, Company Name, etc.) One of the fields, a TextBox, is a
PromoCode which is a field required for each company which registers.
I want to programatically set the value of this PromoCode in the host
web-form's Page_Load method, but I can't seem to do it.

My user control is "RegisterInfo.ascx" (On the page it is rendered as
"RegisterInfo1")
My main web page is Register.aspx

In the Register.aspx.cs code-behind file I would like to do something
like:

private void Page_Load(object sender, System.EventArgs e)
{
this.RegisterInfo1.PromoCode.Text = "PROMOCODE";
}

But, of course, it didn't work. So, I tried...

private void Page_Load(object sender, System.EventArgs e)
{
RegisterInfo r = new RegisterInfo();
r._promoCode.Text = "PROMOCODE";
}

And in the user control Register.ascx, I had this:

public string _promoCode
{
get
{return this.PromoCode.Text; // "PromoCode" is the TextBox object.
}
set
{PromoCode.Text = value;
}
}

This complies fine, but I get an "Object reference not set to an
instance of an object." error.

Specifically, how do I set the value of a TextBox in a user control
from the code-behind file? This is not very clear!

Thanks in advance!
 
Try the FindControl() method to identify the child control from the parent.
You can then test for null to make sure you got something back, and cast it
to use member properties. Unless subcontrols of your usercontrol are linked
to properties in the UserControl, you'll have to reference the subcontrols
by reference, not by object navigation.

TextBox nestedTextBox =
thisPage.MyUserControlInstance.FindControl("Firstname") as TextBox;
if(nestedTextBox == null) throw new Exception ("Couldn't find the nested
control");
nestedTextBox.Text = "PROMO";

Hope this helps.
D
 
Thanks! That did point me in the right direction.

For the benefit of others, here's what I coded in my Page_Load method:

TextBox tbPromoCode =
Page.FindControl("ucRegister1").FindControl("PromoCode") as TextBox;
tbPromoCode.Text = "BLAH";

"ucRegister1" is my User Control on the web page

Thanks again!
 
Back
Top