[英]How do I check if items already exist in a ToolStripMenuItem DropDownItems?
[英]How do i check if i tem already exist in ToolStripMenuItem.DropDownItems?
我有一個ToolStripMenuItem
MouseEnter
事件:
private void recentFilesToolStripMenuItem_MouseEnter(object sender, EventArgs e)
{
for (int i = 0; i < lines.Length; i++)
{
ToolStripMenuItem s = new ToolStripMenuItem(lines[i]);
if (!recentFilesToolStripMenuItem.DropDownItems.ContainsKey(lines[i]))
recentFilesToolStripMenuItem.DropDownItems.Add(s);
}
}
現在,我正在使用ContainsKey
但是在我只嘗試使用Contains(s)之前,在這兩種情況下,它都會不斷地將這些項一次又一次地添加到DropDownItems中。 每次我移動鼠標並按Enter時,我都會看到再次添加的項目。 在這種情況下,行是包含文本文件的路徑和名稱的字符串數組。
例如d:\\mytext.txt
索引0中,我看到: d:\\mytext.txt
問題是當我用鼠標進入並且我只希望將它們添加一次時,它會繼續添加它們。
我第一次看到用鼠標進入時:
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
下次當我用鼠標進入時,會看到兩次:
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
然后下一次我看到相同的項目9次,依此類推。
有兩種方法可以做到這一點。
一種是您像這樣創建ToolStripMenuItem
:
new ToolStripMenuItem(lines[i], (Image)null, (EventHandler)null, lines[i]);
第四個參數是.ContainsKey(...)
的“鍵”,而不是第一個參數。
二,您可以通過以下方式進行操作:
if (!recentFilesToolStripMenuItem.DropDownItems
.Cast<ToolStripMenuItem>()
.Any(x => x.Text == lines[i]))
{
recentFilesToolStripMenuItem.DropDownItems.Add(s);
}
第二種方法搜索實際文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.