Reputation: 21
I created a button that generate some textboxes, but I don't know how to get the respective textboxes values. I found some similar idea only using asp.net c#, but I think that's a bit different. This is my code:
public partial class Form1 : Form
{
int control = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = control * 25;
txt.Left = 100;
txt.Name = "TextBox" + this.control.ToString();
control = control + 1;
}
Can someone help me?!
Upvotes: 0
Views: 1734
Reputation: 74605
Well, you've added the Text boxes to this.Controls
so you can go rummaging in there to find them again
foreach(var c in this.Controls){
if(c is TextBox t && t.Name.StartsWith("TextBox"))
MessageBox.Show(t.Text);
I'd pick better names for Name than "TextBox"+integer but so long as you don't name other text boxes that you don't want to consider with the same prefix this will pick up only those you added dynamically
If you know the controls by name I,e, you know that you want the address and that the user has certainly typed it into TextBox 2, you can just access Controls indexed by that name:
this.Controls["TextBox2"].Text;
Doesn't even need casting to a TextBox.. all Controls have a text property
Upvotes: 2
Reputation: 3767
You can call Control.ControlCollection.Find(String, Boolean) Method to get the textbox you want.
string text = ((TextBox)this.Controls.Find("textboxname", true)[0]).Text;
Upvotes: 1
Reputation: 1163
When you have the instance of the textbox, you can get the value by reading the Value property. One way to get the instance is to search it the Controls list, when you give the texbox a unique name.
{
TextBox txt = new TextBox();
txt.Name = "UniqueName";
Controls.Add(txt);
}
{
foreach(var control in Controls)
if (control is TextBox tb && tb.Name == "UniqueName")
return tb.Value;
}
Upvotes: 1