我目前正在使用此方法匹配完全字符串,并在列表框中选择它所属的索引:
private void searchbtn_Click(object sender, EventArgs e)
{
string term = searchbox.Text;
int index = memlist.FindString(term);
if (index != -1)
memlist.SetSelected(index, true);
}
是否可以选择所有部分匹配的字符串? 我该怎么做呢?
答案 0 :(得分:2)
您可以使用以下代码,它选择以字符串开头的项目索引,然后迭代它们并设置所选项目:
memlist.ClearSelected(); // clear previous selection
memlist.Items.Cast<object>()
.Select((item, index) => new { Text = memlist.GetItemText(item), Index = index })
.Where(x => x.Text.StartsWith(term, StringComparison.CurrentCultureIgnoreCase))
.ToList()
.ForEach(x => memlist.SetSelected(x.Index, true));
BTW别忘了将ListBox的SelectMode
设置为多选。
您还可以在foreach循环中选择项目:
var indexesToSelect = memlist.Items.Cast<object>()
.Select((item, index) => new { Text = memlist.GetItemText(item), Index = index })
.Where(x => x.Text.StartsWith(term, StringComparison.CurrentCultureIgnoreCase))
.Select(x => x.Index);
foreach(int index in indexesToSelect)
memlist.SetSelected(index, true);