简体   繁体   中英

How to get dynamic textbox value c#?

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?!

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

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;
}

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;

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