2013-03-18 43 views
0

我有一個Form,它包含一個Menu兩個條目,它們是菜單工具。兩個Menues有一些SubMenus在C#中啓用和禁用ToolStripMenu條目?

現在我有一個TextBox稱爲txtSelectButtonbtnVisible,如果我在TextBox進入1,2,該SubMenu S IN的Menu應該是不可見。我寫了下面的代碼,它是硬編碼的。

ToolStripMenuItem[] mstrip = new ToolStripMenuItem[] { msO1, msO2, msO3, msP1, msP2, msP3 }; 
if (txtSelect.Text.Length > 2) 
{ 
    string word = txtSelect.Text; 
    string[] splt = word.Split(','); 
    for (int x = 0; x < mstrip.Length; x++) 
     mstrip[x].Visible = true; 
    for (int x = 0; x < splt.Length; x++) 
    { 
     int y = Convert.ToInt32(splt[x].ToString()) - 1; 
     if (y >= 0 && y < mstrip.Length) 
      mstrip[y].Visible = false; 
     textBox1.AppendText(mstrip[y].Text); 
     textBox2.AppendText(mstrip[y].OwnerItem.Text); 
    } 
} 

我想在Button Click事件使用foreach環代替,並試圖用下面的,但結果是不一樣的,與上面的代碼。

foreach (ToolStripMenuItem mnItem in msMenus.Items) 
{ 
    MessageBox.Show(mnItem.Text); 
    for (int i = 0; i < mnItem.DropDown.Items.Count; i++) 
    { 
     MessageBox.Show(mnItem.DropDown.Items[i].Text); 
     mnItem.DropDown.Items[i].Visible = true; 
    }  
} 
+0

能否請您澄清這個問題嗎?你需要做什麼? – stevepkr84 2013-03-18 09:27:23

+0

我希望上面的驗證與foreach循環....我不想硬編碼..., – 2013-03-18 09:28:42

回答

0

嗯,可能是你想要的東西,如:

List<Int32> lstindex = new List<Int32>(); 
String[] splt = txtSelect.Text.Split(','); 

// initialize list of indexed for textbox 
foreach (String str in splt) 
{ 
    lstindex.Add(Convert.ToInt32(str) - 1); 
} 

// for each menu 
foreach (ToolStripMenuItem mnItem in msMenus.Items) 
{ 
    // for each menu item 
    foreach (ToolStripItem item in mnItem.DropDown.Items) 
    { 
     // if index of item is in the list of indexed, set visible to false, otherwise to true 
     item.Visible = lstindex.Contains(mnItem.DropDown.Items.IndexOf(item)) ? false : true; 
    } 
} 
+0

我想所有菜單的子項應按順序....,像1,2,3,4,5 ,6,7,8,9,10 ............, – 2013-03-18 11:29:21