Reputation: 25
I'm just learning how to code in c# and I'm trying to figure out a way to search and filter out results from a listbox that contains data. Right now I have a listbox and a search button, my listbox contains website history, and my search button finds the item in the list but I cannot find a way to filter out the other items so that only what I searched for in the textbox appears in the listbox. Right now my search button looks like this. Any ideas?
private void searchBtn_Click(object sender, EventArgs e)
{
listBoxHist.SelectedItems.Clear();
for (int i = 0; i < listBoxHist.Items.Count; i++)
{
if (listBoxHist.Items[i].ToString().Contains(textboxSearch.Text))
{
listBoxHist.SetSelected(i, true);
}
}
}
Upvotes: 2
Views: 1018
Reputation: 67
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBox1.Items.Add("B");
ListBox1.Items.Add("A");
ListBox1.Items.Add("P");
ListBox1.Items.Add("X");
ListBox1.Items.Add("F");
ListBox1.Items.Add("S");
ListBox1.Items.Add("Z");
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String txt=txtsearch.Text;
if (ListBox1.Items.FindByText(txt)!= null)
{
// ListBox1.Items.FindByText(txt).Selected = true;
Response.Write("<script> alert('Item found.');</script>");
}
else
{
Response.Write("<script> alert('Item Not found.');</script>");
}
}
}
Upvotes: 0
Reputation: 216293
There is a well know 'trick' to remove items while iterating over a collection. You should iterate backwards (from the last item through the first) using the for...loop.
In this way, when you remove an item you don't affect the condition used to exit the loop and you are guaranteed that every item is evaluated.
private void searchBtn_Click(object sender, EventArgs e)
{
for (int i = listBoxHist.Items.Count - 1; i >= 0; i--)
{
if (listBoxHist.Items[i].ToString().Contains(textboxSearch.Text))
listBoxHist.SetSelected(i, true);
else
listBoxHist.Items.RemoveAt(i);
}
}
If you do this code while looping forward you will have problem to evaluate correctly every item. Suppose you remove an item when the index is 3. What happens to item in position 4? It slides down one position and now it occupies the position 3 and this happens to every other item after. Now your loop will increment the index to 4 and will start evaluating the item that was at position 5 before the call to RemoveAt. You have skipped the evaluation of an item.
Upvotes: 1