2015-04-23 25 views
0

我有一個方法來重置我的表單上的一些控件。除了名爲「tsStatusLabelInfo」的ToolStripStatusLabel之外,我可以使用該方法。該控件不會傳遞給resetForm()方法。如何更新ToolStripStatusLabel文本通過表單上的所有控件

我相信它是StatusStrip控件的一部分,但我還沒有弄清楚如何訪問ToolStripStatusLabel控件來更新文本。

private void resetButton_Click(object sender, EventArgs e) 
{ 
    Utilities.resetForm(this); 
} 

public static void resetForm(Control form) 
{ 
    foreach(Control c in GetOffSprings(form)) 
    { 
     if (c.Name == "folderTextBox") 
     { 
      ((TextBox)c).Clear(); 
     } 
     else if (c.Name == "mfrListTextBox") 
     { 
      ((RichTextBox)c).Clear(); 
     } 
     else if (c.Name == "mfrListDataGridView") 
     { 
      ((DataGridView)c).DataSource = null; 
     } 
     else if (c.Name == "onlyRadioButton") 
     { 
      ((RadioButton)c).Checked = true; 
     } 
     else if (c.Name == "usRadioButton") 
     { 
      ((RadioButton)c).Checked = true; 
     } 
     else if (c.Name == "otherYearsCheckedListBox") 
     { 
      ((CheckedListBox)c).SetItemCheckState(0, CheckState.Unchecked); 
      ((CheckedListBox)c).SetItemCheckState(1, CheckState.Unchecked); 
     } 
     else if (c.Name == "yearComboBox") 
     { 
      ((ComboBox)c).Text = string.Empty; 
     } 
     else if (c.Name == "tsStatusLabelInfo") 
     { 
      //Control never pass 
     } 
     else if (c.Name == "statusStrip1") 
     { 
      // Exception:Object reference not set to an instance of an object 
      ((StatusStrip)c).Controls["tsStatusLabelInfo"].Text = string.Empty; 
     } 
    } 
} 

//Loop through the control recursively getting all child controls 
public static IEnumerable<Control> GetOffSprings(this Control @this) 
{ 
    foreach(Control child in @this.Controls) 
    { 
     yield return child; 

     //MessageBox.Show(child.Name); 

     foreach (var offspring in GetOffSprings(child)) 
     { 
      yield return offspring; 
     } 
    } 
} 

回答

0

正是因爲這一點:https://msdn.microsoft.com/en-us/library/system.windows.forms.toolstrip.controls(v=vs.110).aspx

Controls收集未在ToolStripToolStripContainer使用。您應該使用Items代替:https://msdn.microsoft.com/en-us/library/system.windows.forms.toolstrip.items(v=vs.110).aspx

工具條上的項目不是Control對象。他們是ToolStripItem對象。通過Controls集合遞歸循環不會讓您訪問這些項目。

+0

這樣做 - 我將代碼更改爲 ((StatusStrip)c).Items [「tsStatusLabelInfo」] .Text = string.Empty; 感謝您的幫助! – Joaquin

相關問題