Pyromancer Pyromancer - 2 months ago 24
C# Question

show/ hide items in the listbox

I make a listbox and it works perfectly, I also made a search function, but I want to hide the items in the listbox and show them only when searched through index.
here is my code for adding items

private void Savebtn_Click(object sender, EventArgs e)
{
addTolist(gatherItem());
refreshView();
}
private void addTolist(Person p)
{
Person.listperson.Add(p);
}
private void refreshView()
{
listBox1.Items.Add(getItem());
}

private String getItem()
{
String result = null;
foreach (Person p in Person.listperson)
{
result = p.lastname;
}
return result;
}


and this is my code for search

private void button1_Click(object sender, EventArgs e)
{
int index = listBox1.FindString(textBox6.Text);
if (0 <= index)
{
listBox1.SelectedIndex = index;
}
}


Is there a way for this? thanks :)

Answer

There is no easy way to do this with winforms. It a lot easier with WPF. With winforms you will have to remove the items. You could technically use databinding, but its not recommended at all, because listbox is supposed to used directly from your code according the MSDN documentation.

On second thought, you could overdraw the listbox and set the item you want to hide to transparent or something, buts its not easy. You may want to consider storing all your values in an array and then loop through array and only adding the elements you want. Or switch to WPF.

Hope this helps.