2014-01-24 16 views
0

我想從多個表單(Main,Two和Three)獲取所有控件,並且 比較控件標記是否等於變量str_name,如果爲true,則在c中寫入str_value的 值。文本。從csharp獲取多個表單的所有控件

代碼:

private static Form[] getformular() 
{ 
    Main main = new Main(); 
    Two f2 = new Two(); 
    Three f3 = new Three(); 
    Form[] form = { main, f2, f3}; 
    return form; 
} 

private void initcontrol() 
{ 
    String str_name = "name"; 
    String str_value = "value"; 
    foreach(Form f in getformular()) 
    { 
     foreach (Control c in f.Controls) 
     { 
      if (f != null && c = null) 
      { 
       if (c.Tag.Equals(str_name)) 
       { 
        c.Text = str_value; 
       } 
      } 
     } 
    } 
} 

能否請人幫我嗎?

+1

我強烈建議仔細看看數據綁定,因此您不需要爲此目的重新發明輪子。 – Robert

+0

你能解釋一下你爲什麼要這樣做,爲什麼你不能直接命名你的TextBox,比如'nameTextBox'並直接獲取它? –

+0

更好的是,如果你想在每個文本框中使用默認值,就把它放在設計器中。 – DonBoitnott

回答

0

首先,如@JonB所述,當前代碼中的一些條件檢查(if s邏輯)似乎關閉。

其次,循環遍歷Form.Controls只會將所有控件直接放置在窗體中。例如,如果您將選項卡控件(或任何其他容器控件)放置在窗體中,並且該選項卡控件內有一個文本框,則只會得到選項卡控件,並且無法通過循環訪問Form.Controls來找到該文本框。你可以用下面演示的遞歸方法解決這個問題。

private void initcontrol() 
{ 
    String str_name = "name"; 
    String str_value = "value"; 
    var result = false; 
    foreach(Form f in getformular()) 
    { 
     //if you want to check if f null, it should be here. 
     if(f != null) result = setControlText(f, str_name, str_value); 
    } 
    if(!result) MessageBox.Show("Control not found"); 
} 

private bool setControlText(Control control, string str_name, string str_value) 
{ 
    var isSuccess = false; 
    foreach (Control c in control.Controls) 
    { 
     //if c is not null 
     if (c != null) 
     { 
      //check c's Tag, if not null and matched str_name set the text 
      if (c.Tag != null && c.Tag.Equals(str_name)) 
      { 
       c.Text = str_value; 
       isSuccess = true; 
      } 
      //else, search in c.Controls 
      else isSuccess = setControlText(c, str_name, str_value); 

      //if control already found and set, exit the method now 
      if (isSuccess) return true; 
     } 
    } 
    return isSuccess; 
} 
相關問題