2017-02-23 17 views
1

我在我的Form中有16個文本框,其名稱分別從1到16的順序後綴。如何根據其名稱中的索引ID訪問一組文本框

即16個測試框名稱爲TextBox1,'TextBox2 , .... all the way until the 16th one, which is named TextBox16`。

我想在一個循環中讀取這16個文本框的內容,並根據一定的條件修改第12個TextBox的內容或屬性。

我該怎麼做?

+1

爲什麼不使用的文本框的陣列? – dumetrulo

+0

http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type試試這個。 – Adrian

+0

進行了語法修正並添加了一些示例,以幫助觀衆更好地理解所要提問的內容,以便他們提供有用的答案/解決方案。 – Shiva

回答

0

如果您使用的WinForms,最簡單的方法是存儲文本框引用數組,在窗口的構造函數: TextBox[] data = new TextBox[16]{textBox1,textBox2, [...],textBox16};

,那麼你可以使用循環來訪問它們。

0

你可以嘗試這樣的事情:

Dictionary<string, string> yourValues = new Dictionary<string, string>(); 
    foreach (Control x in this.Controls) 
    { 
     if (x is TextBox) 
     { 
      yourValues.Add(((TextBox)x).Name, ((TextBox)x).Text); 
     } 
    } 

注:在你的未來的問題,請提供更多的信息,使您的問題更加清晰。

0

我會嘗試找到並使用修改的Linq:

using System.Linq; 
//... 

int x = 5; //number of textbox to search 
var textbox = this.Controls.OfType<TextBox>().Single(tb => tb.Name.EndsWith(x.ToString())); 
textbox.Text = "abc"; 

如果您有循環直通形式的所有texboxes,你可以做這樣的事情:

List<TextBox> textboxes = this.Controls.OfType<TextBox>().ToList(); 
foreach (TextBox box in textboxes) 
{ 
    box.Text = "something"; 
} 
0

最簡單的方法根據你指定的是使用Linq

讓我們假設你有3個TextBox ES:

// 1st -> which is named meTextBox1 
// 2nd -> which is named meTextBox2 
// 3rd -> which is named meTextBox3 

你可以從每一行上面只能看到數不同(指數..叫它任何你想要的)。

現在你可以讓你的基地「查詢」,它看起來像:

const string TB_NAME = "meTextBox{0}"; 

正如你現在可以相信這將string.Format方法內部使用。現在要檢索所需TextBox所有你需要做的就是讓Linq聲明:

string boxName = string.Format(TB_NAME, 7); // retrieve 7th text box 
TextBox tBox = Controls.OfType<TextBox>().FirstOrDefault(tb => tb.Name == boxName); 

這個例子沒有考慮嵌套Control秒,但你可以做到這一點遞歸這將檢索嵌套Control S:

TextBox ByIndex(int idx, Control parent) 
{ 
    TextBox result = null; 
    string searchFor = string.Format(TB_NAME, idx); 
    foreach(Control ctrl in parent.Controls) 
    { 
     if(!(ctrl is TextBox) && ctrl.HasChildren) 
     { 
      result = ByIndex(idx, ctrl); 
      if(result != null) 
       break; 
     } 
     else if(ctrl is TextBox) 
     { 
      if(ctrl.Name = searchFor) 
      { 
       result = ctrl as TextBox; 
       break; 
      } 
     } 
    } 
    return result; 
} 

要使用上面的方法,你可以叫它像這樣:

public class MeForm : Form 
{ 
    //.. your code here .. 

    void meImaginaryMethodToRetrieveTextBox() 
    { 
     int meRandomIndex = 7; 
     TextBox tb = ByIndex(meRandomIndex, this); 
     // rest of the code... 
    } 
} 
相關問題