c# - Retrieve checked Items in checkedListBox from text file -
i have text file 1 word per line represents checkedlistbox have checked previously. when application re-run want checkedlistbox items checked, i've tried:
system.io.streamreader file = new system.io.streamreader(@"checked.txt"); foreach (var checked in file.readline()) { lstcheckbox.setitemchecked(checked, true); }
this doesn't seem work, whilst debugging application crashes, ideas i'm going wrong?
error:
invalidargument=value of '97' not valid 'index'. parameter name: index
fixed
foreach (var checked in file.readalllines(@"checked.txt")) { int index = lstcheckbox.items.indexof(checked); if (index > 0) { lstcheckbox.setitemchecked(index, true); } }
this because readline
returns single line, , you're iterating characters in line.
string line; while ((line = file.readline()) != null) { var index = int.parse(line); lstcheckbox.setitemchecked(checked, true); }
should fix problem.
alternatively, use following code instead (not using streamreader
).
foreach (var line in file.readalllines("checked.txt")) { var index = int.parse(line); lstcheckbox.setitemchecked(checked, true); }
Comments
Post a Comment