【问题标题】:Get value of dynamically created textbox获取动态创建的文本框的值
【发布时间】:2015-02-02 11:17:50
【问题描述】:

我现在有点迷茫,我创建了一些代码来创建 4 个文本框并在运行时将它们添加到表格布局中(下面的代码),但我正在努力获取文本从中,我尝试像 string s = TxtBox1.Text.ToString(); 一样从中获取值,但它只是获得一个空引用,然后我尝试了 txt.Text.ToString();,这只是从创建的最后一个文本框中获取文本。

   private void button2_Click(object sender, EventArgs e)
    {
        int counter;
        for (counter = 1; counter <= 4; counter++)
        {
            // Output counter every fifth iteration
            if (counter % 1 == 0)
            {
                AddNewTextBox();
            }
        }
    }

    public void AddNewTextBox()
    {
        txt = new TextBox();
        tableLayoutPanel1.Controls.Add(txt);
        txt.Name = "TxtBox" + this.cLeft.ToString();
        txt.Text = "TextBox " + this.cLeft.ToString();
        cLeft = cLeft + 1;
    }

我已经到处寻找这个问题的答案,但如果有人有任何想法,我将不胜感激。

谢谢

【问题讨论】:

    标签: c# winforms dynamic textbox


    【解决方案1】:

    此代码从 tableLayoutPanel1 中选择 textbox1,将其从 Control 转换为 TextBox 并获取 Text 属性:

    string s = ((TextBox)tableLayoutPanel1.Controls["TxtBox1"]).Text;
    

    如果你需要它们,然后遍历文本框:

    string[] t = new string[4];
    for(int i=0; i<4; i++)
        t[i] = ((TextBox)tableLayoutPanel1.Controls["TxtBox"+(i+1).ToString()]).Text;
    

    【讨论】:

    • 很棒的东西,我对我正在尝试的一些事情非常接近,我设法在没有强制转换的情况下获得了第一个代码块。我出于某种原因决定我走错了路
    • 如果tableLayout 也动态创建会怎样
    【解决方案2】:

    你可以试试

        var asTexts = tableLayoutPanel1.Controls
                .OfType<TextBox>()
                .Where(control => control.Name.StartsWith("TxtBox"))
                .Select(control => control.Text);
    

    这将枚举 tableLayoutPanel1 的所有子控件的 Text 值,其中它们的类型是 TextBox 并且它们的名称以“TxtBox”开头。 您可以选择放宽过滤器,删除 OfType 行(排除任何非 TextBox 控件)或 Where 行(仅允许名称与您的示例匹配的控件)。

    确保有

        Using System.Linq;
    

    在文件的开头。 问候, 丹尼尔。

    【讨论】:

      【解决方案3】:
          public void AddNewTextBox()
          {
              txt = new TextBox();
              tableLayoutPanel1.Controls.Add(txt);
              txt.Name = "TxtBox" + this.cLeft.ToString();
              txt.Text = "TextBox " + this.cLeft.ToString();
              cLeft = cLeft + 1;
              txt.KeyPress += txt_KeyPress;
          }
      
      
          private void txt_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
          {
              //the sender is now the textbox, so that you can access it
              System.Windows.Forms.TextBox textbox = sender as System.Windows.Forms.TextBox;
              var textOfTextBox = textbox.Text;
              doSomethingWithTextFromTextBox(textOfTextBox);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 2012-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多