Reputation: 19
I want to create a TextBox
dynamically in form and retrieve its data and paste it into another TextBox in the same form when I click a button.
I used the following code for creating texboxes dynamically :
public int c=0;
private void button1_Click(object sender, EventArgs e)
{
string n = c.ToString();
txtRun.Name = "textname" + n;
txtRun.Location = new System.Drawing.Point(10, 20 + (10 * c));
txtRun.Size = new System.Drawing.Size(200, 25);
this.Controls.Add(txtRun);
}
I need the code for retrieving data from this TextBox
Upvotes: 1
Views: 926
Reputation:
You are not creating the Textbox
instance in your routine:
TextBox txtRun = new TextBox();
//...
string n = c.ToString();
txtRun.Name = "textname" + n;
txtRun.Location = new System.Drawing.Point(10, 20 + (10 * c));
txtRun.Size = new System.Drawing.Size(200, 25);
this.Controls.Add(txtRun);
When you need the content:
string n = c.ToString();
Control[] c = this.Controls.Find("textname" + n, true);
if (c.Length > 0) {
string str = ((TextBox)(c(0))).Text;
}
Or cache your instance in a private array if you need frequent look-ups on it.
The routine assumes it get a Textbox
in index 0. You should of course check for null
and typeof
.
Upvotes: 1
Reputation: 8656
Based on your question, you could use something like this:
string val = string.Empty;
foreach (Control cnt in this.Controls)
{
if(cnt is TextBox && cnt.Name.Contains("textname"))
val = ((TextBox)cnt).Text;
}
Although I don't see where you are making new instances of the TextBox
when you are adding them to the form.
Upvotes: 0