2013-10-28 70 views
-1

我有50個文本框從TextBox1開始,直到TextBox50。我想從所有這50個文本框中檢索值。我嘗試循環但失敗。我想要一些代碼,如TextBox(i).Text,其中我從1到50變化。 循環應產生以下結果。 Response.Write(TextBox1.Text); Response.Write(TextBox2.Text); 兒子直到 Response.Write(TextBox50.Text);從C#中的文本框中檢索文本的循環文本框ID

我該如何做到這一點?

+0

'我試過循環,但它failed'請顯示你的代碼。你是什​​麼意思「失敗」?編譯錯誤?運行時異常?意外的輸出?更加詳細一些。 – tnw

回答

3

您可以使用FindControl這需要一個字符串作爲參數,通過它"TextBox" + i喜歡:

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

+1,尼斯解決方案!我正在建議製作一個陣列。 – gleng

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 
    } 
}