循环文本框 ID,用于从 C# 中的文本框中检索文本

本文关键字:文本 检索 用于 ID 循环 | 更新日期: 2023-09-27 18:37:14

>我有50个文本框,从TextBox1到TextBox50。我想从所有这 50 个文本框中检索值。我尝试循环,但失败了。我想要一些像TextBox(i)这样的代码。i 从 1 到 50 变化的文本。循环应生成以下结果。Response.Write(TextBox1.Text);Response.Write(TextBox2.Text); 儿子在蒂尔Response.Write(TextBox50.Text);

我怎样才能做到这一点?

循环文本框 ID,用于从 C# 中的文本框中检索文本

您可以使用

FindControl,它将字符串作为参数,将其传递"TextBox" + i如下所示:

TextBox tb = this.FindControl("TextBox" + i) as TextBox;
if (tb != null)
{
    Response.Write(tb.Text);
}

您可以简单地将它们循环如下:

string value=""; // store each textbox value in this variable
foreach (Control x in this.Controls) // loop through the controls in the form
{
   if (x is TextBox) // if the program found a textbox in the form
   {
      value = (x as TextBox).Text; // set the value of the textbox number x to the string value
      listBox1.Items.Add(value); // here is a listbox to show the resule
   }
}