Reputation: 1148
I am currently using this method to match exact strings and select the index of which it belongs in a Listbox:
private void searchbtn_Click(object sender, EventArgs e)
{
string term = searchbox.Text;
int index = memlist.FindString(term);
if (index != -1)
memlist.SetSelected(index, true);
}
Would it be possible to have all partially matching strings selected? How would I have to go about doing that?
Upvotes: 1
Views: 491
Reputation: 236188
You can use following code, which selects indexes of items, which start with your string, and then iterate over them and set items selected:
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 Don't forget to set SelectMode
of ListBox to multi select.
You can also select items in foreach loop:
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);
Upvotes: 2