简体   繁体   中英

Dynamic textbox creation in form

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM