Get the Text of Dynamically Created Text Box


In this article, you will know how to Get the Text of Dynamically Created Text Box. Learn something about Get the Text of Dynamically Created Text Box.

Find the code for Get the Text of Dynamically Created Text Box

In following code snippet I will be creating a control dynamically on a button click and on another button click I will display the value of the dynamically created control.

For this example, please create a window application and a Panel control and 2 buttons to Form1.

Now add following code in button1’s click event, in this event create a TextBox control dynamically and add that to Panel1

private void button1_Click(object sender, EventArgs e)
{
//Create a object for Textbox
TextBox txt = new TextBox();
txt.Text = "";
//Assign name
txt.Name = "TextBox10";
txt.Width = 560;
txt.Height = 48;
txt.Location = new System.Drawing.Point(15, 66);
//Add that control to Panel
Panel1.Controls.Add(txt);
}


Once created the control now to retrieve the value of the Dynamically created control, add following code in Button2’s click event


private void button2_Click(object sender, EventArgs e)
{
//Find control in the Panel with Name
Control[] ctrls = Panel1.Controls.Find("TextBox10", false);
//Loop through the controls and find the control
for (int i = 0; i < ctrls.Length; i++)
{
//Create textbox object back from control object
TextBox txtBox = (TextBox)ctrls[0];
//Display its Test
MessageBox.Show(txtBox.Text);
}
}


Now we are ready with our code lets build, run and test

Tag : Read the value of Dynamically created Control


Satish Kumar J
Microsoft MVP(ASP.NET)


Comments

Guest Author: Rashmi05 Dec 2011

A great article. proved very usefull. it helped to save a lot of my time.Thank you very much.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: