2015-09-28 27 views
3

如何从文本文件获取值并选择具有该值的复选框?如何从文本文件中获取值并选择具有该值的复选框?

我使用此代码试图让谁是后等于值:

string installerfilename = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "installer.ini"); 
      IEnumerable<string> inilines = File.ReadAllLines(installerfilename).AsEnumerable(); 

      string selectedItem = checkedListBox1.SelectedItem.ToString(); 
      bool IsChecked = checkedListBox1.CheckedItems.Contains(selectedItem); 
    inlines = inlines.Select(line => line == string.Format("‪product‬={0}", selectedItem)) 
        ? Regex.Replace(line, string.Format("product={0}", selectedItem), string.Format(@"product={0}", selectedItem)) : line); 

也是我这个尝试:

foreach (var line in inilines) 
      { 
       if (line.Contains("product={0}")) 
       { 
        IsChecked = true; 
        //checkedListBox1.CheckedItems =true; 
       } 

,但我不知道如何从勾选一个CheckedListBox谁拥有相同的行后的值如何product="name of checkbox"

回答

2

你可以这样做:

var lines = System.IO.File.ReadAllLines(@"D:\Test.txt"); 

lines.ToList() 
    .ForEach(item => 
    { 
     //check if item exists in CheckedListBox set it checked. 
     //We find the index of the item, -1 means that item doesn't exists in CheckedListBox 
     var index = this.checkedListBox1.Items.IndexOf(item); 
     if(index >=0) 
      this.checkedListBox1.SetItemChecked(index, true); 
    }); 

注:

  • 使用文件保存和恢复您的托运物品代替,最好是使用一个设置属性来保存您的检查项目。

检查所有项目:

要通过它的索引,哟UCAN使用this.checkedListBox1.SetItemChecked(i, true);检查项目,因此对于检查所有项目,你可以这样做:

for (int i = 0; i < this.checkedListBox1.Items.Count; i++) 
{ 
    this.checkedListBox1.SetItemChecked(i, true); 
} 

针对您的特殊案例:

你有一个文件包含:

product=item1 
#product=item2 
#product=item3 
product=item4 

这意味着物品1和ITEM4应进行检查,你可以使用WhereSelect选择从线需要的东西,例如:

lines.Where(x=>!x.StartsWith("#")) 
    .Select(x=>x.Replace("Product=","").Trim()) 
    .ToList() 
    .ForEach(item => 
    { 
     var index = this.checkedListBox1.Items.IndexOf(item); 
     if(index >=0) 
      this.checkedListBox1.SetItemChecked(index, true); 
    }); 
+0

以及我如何做,在文本文件我的产品=全部选中所有复选框? – ben

+0

@ben只要检查第一行,如果第一行是全部,就为所有索引调用SetItemChecked –

+0

@ben,但我不是更好地保存“all”来保存已检查的项目。 –

相关问题