1

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

2
  • What have you tried to retrieve data from TextBoxes ? You need to know that StackOverFlow ansewers won't do your job. Commented Oct 21, 2012 at 10:41
  • 1
    "I need the code" is not a good question. Please rephrase it or this question is likely to be closed. You need to tell us the problems you are experiencing. Can't you find the textbox in your other method? What specific TextBox is it that you cant get the text of, txtRun? How are you creating txtRun btw? Commented Oct 21, 2012 at 11:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.