Miguel
Miguel

Reputation: 79

How to retrieve text from a TextBox that was created programatically

Alright, so I have a form set up that contains a label and a button. When the button is pressed it creates several labels and and two textfields in a specific area.

I cannot for the life of me, figure out how to retrieve the text from those textfields and store it in a public string.

Any help would be wonderful and greatly appreciated.

Edit: As per request.

        TextBox playertextbox = new TextBox();
        playertextbox.Location = new Point(460, 200);
        this.Controls.Add(playertextbox);

Upvotes: 1

Views: 238

Answers (1)

Amitd
Amitd

Reputation: 4849

You can assign a name to the textbox and later use ControlCollection.Find to retrieve it
Try this

TextBox playertextbox = new TextBox();
playertextbox.Location = new Point(460, 200);
playertextbox.Name = "playertxtBox"; // Add some name
this.Controls.Add(playertextbox);

Then use the name in the button click handler or similar :

 //Use that name to search here
 TextBox playertextbox = ((TextBox) this.Controls.Find("playertxtBox",true)[0]); 
 string text = playertextbox.Text;

Upvotes: 3

Related Questions