Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically creating a web control 2

Status
Not open for further replies.

dvknn

IS-IT--Management
Mar 11, 2003
94
US
I am able to create a web control programmatically and display on the form. In the click event of the button then I am trying to capture the value entered in the above created textbox in another click of button but I am unable to obtain the reference of the control that has been created dynamically.


Can anyone help me please?

protected System.Web.UI.WebControls.Panel myPanel;

private void btnMake_Click(object sender, System.EventArgs e)
{
TextBox txtBox = new TextBox();
myPanel.Controls.Add(txtBox);


}
private void btnGotValues_Click(object sender, System.EventArgs e)
{
TextBox myTextBox =(TextBox)myPanel.Controls[1];
lblMessage.Text = myTextBox.Text;
lblMessage.Visible = true;
}
 
You need to keep loading your control, once it's created, otherwise you'll lose a reference to it. Second, the Controls Collection is zero based.
Code:
private void Page_Load(object sender, System.EventArgs e)
{
 if(ViewState["TextBoxCreated"] != null)
 {
  addTextBox();
 }
}
private void addTextBox()
{
  myPanel.Controls.Clear();
  TextBox txtBox = new TextBox();
  myPanel.Controls.Add(txtBox);
}
private void btnMake_Click(object sender, System.EventArgs e)
{
 addTextBox();	
 ViewState["TextBoxCreated"] = true;
}
private void btnGotValues_Click(object sender, System.EventArgs e)
{			
 TextBox myTextBox =(TextBox)PlaceHolder1.Controls[0];
 lblMessage.Text = myTextBox.Text;
 lblMessage.Visible = true;
}
 
Thank you.. your code helped me


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top