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

问题描述 投票:-1回答:2

我有50个文本框从TextBox1开始直到TextBox50。我想从所有这50个文本框中检索值。我试过循环但它失败了。我想要一些代码,如TextBox(i).Text,其中i从1到50不等。循环应产生以下结果。回复于(TextBox1.Text);回复于(TextBox2.Text);儿子直到Response.Write(TextBox50.Text);

我怎样才能做到这一点?

c# asp.net
2个回答
3
投票

您可以使用以字符串作为参数的FindControl,将其传递给"TextBox" + i,如:

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

0
投票

你可以简单地循环思考它们如下:

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
   }
} 
© www.soinside.com 2019 - 2024. All rights reserved.