简体   繁体   English

如何获取动态文本框值 c#?

[英]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.我发现一些类似的想法只使用 asp.net c#,但我认为这有点不同。 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好吧,您已将文本框添加到this.Controls中,因此您可以 go 在那里翻找再次找到它们

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我会为 Name 选择比“TextBox”+integer 更好的名称,但只要您不使用相同的前缀命名您不想考虑的其他文本框,这只会选择您动态添加的那些

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:如果您知道控件的名称 I,e,您知道您想要该地址并且用户肯定已将其输入到 TextBox 2 中,您可以访问按该名称索引的控件:

this.Controls["TextBox2"].Text;

Doesn't even need casting to a TextBox.. all Controls have a text property甚至不需要转换为 TextBox .. 所有控件都有一个 text 属性

When you have the instance of the textbox, you can get the value by reading the Value property.当您拥有文本框的实例时,您可以通过读取 Value 属性来获取值。 One way to get the instance is to search it the Controls list, when you give the texbox a unique name.获取实例的一种方法是在控件列表中搜索它,当您为 texbox 指定一个唯一名称时。

{
    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.您可以调用Control.ControlCollection.Find(String, Boolean) 方法来获取您想要的文本框。

string text = ((TextBox)this.Controls.Find("textboxname", true)[0]).Text;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM