【问题标题】:Retrieve checked Items in checkedListBox from text file从文本文件中检索checkedListBox中的选中项
【发布时间】:2013-08-15 22:57:39
【问题描述】:

我有一个每行一个单词的文本文件,它代表我之前检查过的checkedListBox。现在,当应用程序重新运行时,我希望已经检查了 checkedListBox 项,我已经尝试过:

System.IO.StreamReader file = new System.IO.StreamReader(@"checked.txt");
foreach (var checked in file.ReadLine())
{              
        lstCheckBox.SetItemChecked(checked, true);
}

这似乎不起作用,在调试应用程序崩溃时,有什么想法我哪里出错了吗?

错误:

    InvalidArgument=Value of '97' is not valid for 'index'.
    Parameter name: index

已修复

foreach (var checked in File.ReadAllLines(@"checked.txt"))
{
    int index = lstCheckBox.Items.IndexOf(checked);

    if (index > 0)
    {
        lstCheckBox.SetItemChecked(index, true);
    }
}

【问题讨论】:

  • 你遇到了什么崩溃?
  • @Matthew 更新 OP 时出现错误
  • 复选框列表是否包含至少 98 个项目?另外,SetItemChecked 的第一个参数是一个整数,我没有看到你从字符串进行任何转换。这是完整的代码吗?
  • @Matthew 列表包含 20 项,这是检索的全部代码是的。

标签: c# checkedlistbox


【解决方案1】:

这是因为 ReadLine 返回单行,而您正在迭代该行中的字符。

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

应该解决问题。

或者,您可以改用以下代码(不使用StreamReader)。

foreach (var line in File.ReadAllLines("checked.txt"))
{
    var index = int.Parse(line);
    lstCheckBox.SetItemChecked(checked, true);      
}

【讨论】:

  • >var index = int.Parse(line);返回错误 [输入字符串的格式不正确。]
  • 您的文件包含什么?
  • 一句话,怎么和你的列表框对应?
  • 单词是checkedlistbox项文本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 2012-03-26
  • 2015-06-18
  • 1970-01-01
相关资源
最近更新 更多