Domanda

I have a text file with one word per line which represents the checkedListBox I have checked previously. Now when the application is re-run I want the checkedListBox items to already be 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 to work, whilst debugging the application crashes, any ideas where I'm going wrong?

Error:

    InvalidArgument=Value of '97' is not valid for '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);
    }
}
È stato utile?

Soluzione

This is because ReadLine returns a single line, and you're iterating the characters in the line.

string line;
while ((line = file.ReadLine()) != null)
{
    var index = int.Parse(line);
    lstCheckBox.SetItemChecked(checked, true);  
}

Should fix the problem.

Alternatively, you could use the following code instead (not using StreamReader).

foreach (var line in File.ReadAllLines("checked.txt"))
{
    var index = int.Parse(line);
    lstCheckBox.SetItemChecked(checked, true);      
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top