2012-07-12 58 views
-1

我想訪問多個textbox名稱textbox1,textbox2,textbox3等。通過循環而不是個人名稱。出於這個原因,我創建了一個創建這個var名稱的函數。如何訪問多個按鈕或文本框或任何控件?

public string[] nameCre(string cntrlName, int size) 
{ 
    string[] t = new string[size]; 

    for (int i = 0; i < size; i++) 
    { 
     t[i] = cntrlName.ToString() + (i + 1); 
    } 
    return t; 
} 

nameCre("Textbox",5);所以此,函數返回成功我TextBox1中,TextBox2中...... TextBox5。

但是,當我試圖通過

string[] t = new string[50]; 
t= nameCre("TextBox",5);  
foreach (string s in t) 
{ 
    ((TextBox) s).Text = ""; 
} 

它給我的錯誤這個字符串轉換爲TextBox控件:

無法轉換類型「字符串」到「System.Windows.Forms.TextBox '....

我該如何完成這份工作?

+0

不,你不能!你不能將「字符串」轉換爲「文本框」......你究竟想在這裏做什麼? – 2012-07-12 02:47:52

+0

你已經有文本框「文本框1」,「文本框2」等。你試圖獲取它們並將其文本設置爲「」? – 2012-07-12 02:50:41

+0

@PrateekSingh是的,這就是我想要做的 – 2012-07-12 03:41:17

回答

0
string[] t= new string[50]; 
    t= nameCre("TextBox",5); 

foreach (string s in t){ 
TextBox tb = (TextBox)this.Controls.FindControl(s); 
tb.Text = ""; 
} 

如果你有很多文本框

foreach (Control c in this.Controls) 
{ 
    if (c.GetType().ToString() == "System.Windows.Form.Textbox") 
    { 
    c.Text = ""; 
    } 
} 
0
var t = nameCre("TextBox",5); 

foreach (var s in t) 
{ 
    var textBox = new TextBox {Name = s, Text = ""}; 
} 
0

也許你需要這個 -

 string[] t = new string[50]; 
     t = nameCre("TextBox", 5); 

     foreach (string s in t) 
     { 
      if (!string.IsNullOrEmpty(s)) 
      { 
       Control ctrl = this.Controls.Find(s, true).FirstOrDefault(); 
       if (ctrl != null && ctrl is TextBox) 
       { 
        TextBox tb = ctrl as TextBox; 
        tb.Text = ""; 
       } 
      } 
     } 
+0

我試過這段代碼。我收到很多錯誤: 1)我不能使用var。 「類型或命名空間名稱‘變種’找不到(是否缺少using指令或程序集引用?)」 \t 2)「的System.Array」不包含「FirstOrDefault」 \t 3的定義)無法通過內置轉換將類型'var'轉換爲'System.Windows.Forms.TextBox'。 – 2012-07-12 04:18:03

+0

你使用的是什麼.Net版本? – 2012-07-12 04:55:29

+0

我已經更新了上面的代碼來處理您的例外編號1&3.對於2,在您的代碼中添加System.Linq的引用 - '使用System.Linq'。 – 2012-07-12 05:09:07

0

這個職位是很老,反正我覺得我可以給你(或其他人有這樣的問題)一個答案:

我認爲使用TextBoxs的陣列(或目錄)將是這樣做的最佳解決方案:

 // using an Array: 
     TextBox[] textBox = new TextBox[5]; 
     textBox[0] = new TextBox() { Location = new Point(), /* etc */}; 
     // or 
     textBox[0] = TextBox0; // if you already have a TextBox named TextBox0 

     // loop it: 
     for (int i = 0; i < textBox.Length; i++) 
     { 
      textBox[i].Text = ""; 
     } 

     // using a List: (you need to reference System.Collections.Generic) 
     List<TextBox> textBox = new List<TextBox>(); 
     textBox.Add(new TextBox() { Name = "", /* etc */}); 
     // or 
     textBox.Add(TextBox0); // if you already have a TextBox named TextBox0 

     // loop it: 
     for (int i = 0; i < textBox.Count; i++) 
     { 
      textBox[i].Text = ""; 
     } 

我希望這有助於:)

相關問題