c# - How do i make instance for array of ToolStripMenuItem items? -
in top of form1:
toolstripmenuitem[] items;
in constructor:
for (int = 0; < 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 used single item , made 1 instance in top of form1. want add dropdownitems array of items. , don't how many items want unlimited.
then have event:
private void recentfilestoolstripmenuitem_mouseenter(object sender, eventargs e) { (int = 0; < lines.length; i++) { items[i].text = lines[i]; } }
when used single item did in mouseenter event:
item.text = "hello world";
but want add items text file can 1 items or 200 items problem items null in constructor.
i did in constructor changed 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 case lines.length 3. when on items see 3 items each 1 of them null. know how many items need instance reason null.
it seems, main problem in fact don't know in advance length of items[]
; such problem task linq, that:
private toolstripmenuitem[] items; ...
in constructor:
items = file .readlines(@"e:\recentfiles.txt") .select(line => new toolstripmenuitem() { text = line }) .toarray(); ... // if items used in addrange // have no need neither of toarray() nor in private field recentfilestoolstripmenuitem.dropdownitems.addrange(items);
in case want, say, 10 first recent files only:
items = file .readlines(@"e:\recentfiles.txt") .take(10) .select(line => new toolstripmenuitem() { text = line }) .toarray();
Comments
Post a Comment