Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66058614/how-to-get-dynamic-textbox-value-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...