Reputation: 129
In top of form1:
ToolStripMenuItem[] items;
In constructor:
for (int i = 0; i < items.Length; i++)
{
items[i] = new ToolStripMenuItem();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
}
if (!File.Exists(@"e:\RecentFiles.txt"))
{
recentfiles = new StreamWriter(@"e:\RecentFiles.txt");
recentfiles.Close();
}
else
{
lines = File.ReadAllLines(@"e:\RecentFiles.txt");
}
Before it i used single item and i made one instance for it in the top of form1. But i want to add to the DropDownItems array of items. And i don't how many items i want for it to be unlimited.
Then i have this event:
private void recentFilesToolStripMenuItem_MouseEnter(object sender, EventArgs e)
{
for (int i = 0; i < lines.Length; i++)
{
items[i].Text = lines[i];
}
}
When i used a single item i just did in the MouseEnter event:
item.Text = "hello world";
But now i want to add the items from the text file it can be 1 items or 200 items the problem is that items are null in the constructor.
I did now in the constructor changed it to:
if (!File.Exists(@"e:\RecentFiles.txt"))
{
recentfiles = new StreamWriter(@"e:\RecentFiles.txt");
recentfiles.Close();
}
else
{
lines = File.ReadAllLines(@"e:\RecentFiles.txt");
items = new ToolStripMenuItem[lines.Length];
}
In this case lines.Length is 3. But now when i look on items i see 3 items that each one of them is null. So i know how many items i need to instance but for some reason they are all null.
Upvotes: 0
Views: 1091
Reputation: 186668
It seems, that your main problem is in the fact that you don't know in advance the length of items[]
; such problem is a good task for Linq, something like that:
private ToolStripMenuItem[] items;
...
in the constructor:
items = File
.ReadLines(@"e:\RecentFiles.txt")
.Select(line => new ToolStripMenuItem() {
Text = line
})
.ToArray();
...
// if items are used in AddRange only
// you have no need neither of ToArray() nor in private field
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
in case you want, say, 10 first recent files only:
items = File
.ReadLines(@"e:\RecentFiles.txt")
.Take(10)
.Select(line => new ToolStripMenuItem() {
Text = line
})
.ToArray();
Upvotes: 2