2009-01-05 23 views
0
public void test() 
    { 
     List<int> list = new List<int>(); 
     list.Add(1); 
     list.Add(2); 
     list.Add(3); 
     for (int i = 1; i <= list.Count; i++) 
     { 

      textBx.Text = list[i].ToString(); 
      // I want it to be textBx1.Text = list[1].ToString(); 
           textBx2.Text = list[2].ToString(); 
           textBx3.Text = list[3].Tostring(); 
           etc. 
       // I can't create textbox dynamically as I need the text box to be placed in specific places in the form . How do I do it the best way? 


     } 


    } 

回答

5

聽起來像是Controls.Find()的作業。你可以動態建立字符串,並搜索與該名稱的文本框:

var textBox = this.Controls.Find("textBx" + i, true) as TextBox; 
textBox.Text = list[i].ToString(); 

這是有點難看,因爲它是對文本框的命名約定預測。也許是一個更好的解決辦法是你的循環之前緩存文本框的列表:

var textBoxes = new[] { textBx1, textBx2, textBx3 }; 

那麼你可以簡單索引數組:

textBoxes[i].Text = list[i].ToString(); 
2

+1馬特。這裏是一個可行的完整的解決方案:

 string TextBoxPrefix = "textBx"; 
     foreach (Control CurrentControl in this.Controls) 
     { 
      if (CurrentControl is TextBox) 
      { 
       if (CurrentControl.Name.StartsWith(TextBoxPrefix)) { 

        int TextBoxNumber = System.Convert.ToInt16(CurrentControl.Name.Substring(TextBoxPrefix.Length)); 

        if (TextBoxNumber <= (list.Count - 1)) 
        { 
         CurrentControl.Text = list[TextBoxNumber].ToString(); 
        } 
       } 
      } 
     } 
+0

您可能需要使這個遞歸函數,因爲CurrentControl可以有子控件,例如,如果CurrentControl一張桌子和文本框都各在不同的行/細胞表,我認爲你的功能沒有找到文本框。 – Jeremy 2009-01-05 03:19:39

相關問題