I have a ToolStripMenuItem
MouseEnter
event:
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);
}
}
Now I am using ContainsKey
but before i tried only with Contains(s) In both cases it keep adding the items over and over again to the DropDownItems. Each time i move the mouse and Enter i see the items added again. In this case lines is array of string contain paths and names of text files.
For example in lines index 0 i see: d:\\mytext.txt
The problem is that it keep adding them over again when i enter with the mouse and i want them to be added only once.
First time i see when entering with the mouse:
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
Next time when I enter with the mouse I see it twice:
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
d:\mytext.txt
e:\test.txt
c:\hello\hellowowrld.txt
Then next time i see the same items 9 times and so on.
There are two ways to do this.
One, is that you create your ToolStripMenuItem
like this:
new ToolStripMenuItem(lines[i], (Image)null, (EventHandler)null, lines[i]);
It's that fourth parameter that is the "key" for .ContainsKey(...)
, not the first parameter.
Two, you can do it this way:
if (!recentFilesToolStripMenuItem.DropDownItems
.Cast<ToolStripMenuItem>()
.Any(x => x.Text == lines[i]))
{
recentFilesToolStripMenuItem.DropDownItems.Add(s);
}
This second way searches the actual text.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.