[英]How I can get a value from a text file and select a checkbox who have that value?
How I can get a value from a text file and select a checkbox who have that value ? 如何从文本文件中获取值并选择具有该值的复选框?
I tried with this code to get the value who is after equal: 我尝试使用此代码来获取相等的值:
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);
also I tried with this : 我也试过这个:
foreach (var line in inilines)
{
if (line.Contains("product={0}"))
{
IsChecked = true;
//checkedListBox1.CheckedItems =true;
}
but I don't know how to check the box from a CheckedListBox who have the value after equal for the rows how are like product="name of checkbox"
但是我不知道如何检查CheckedListBox中的框,这些框的行数等于行之后的值,如
product="name of checkbox"
You can do it this way: 你可以这样做:
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);
});
Note: 注意:
Check all Items: 检查所有项目:
To check an item by its index, yo ucan use this.checkedListBox1.SetItemChecked(i, true);
要通过索引检查项目,你可以使用
this.checkedListBox1.SetItemChecked(i, true);
, so for checking all items, you can do: ,所以要检查所有项目,你可以这样做:
for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
{
this.checkedListBox1.SetItemChecked(i, true);
}
For your specific case: 对于您的具体情况:
you have a file containing: 你有一个文件包含:
product=item1
#product=item2
#product=item3
product=item4
That means item1 and item4 should be checked, you can use Where
and Select
to select what you need from lines, for example: 这意味着应该检查item1和item4,你可以使用
Where
和Select
从行中选择你需要的东西,例如:
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.