Reputation: 39
I am learning c# and I started by making some dummy app, with all elements I can practice in it. I have search text field and below I have a list box with items.
I tried with this code but I got result only if I start searching from the first letter. I want to be able to search by letters in between words.
Example: List Item: "0445110085" If I start searching from "0445" I will get results but if I start with "5110" for example I got message item not found.
Below is my code,
private void searchBox_TextChanged(object sender, EventArgs e)
{
string myString = searchBox.Text;
int index = listBox1.FindString(myString, -1);
if (index != -1)
{
listBox1.SetSelected(index,true);
}
else
MessageBox.Show("Item not found!");
}
Thanks in advance.
regards :)
Upvotes: 2
Views: 3653
Reputation: 69
for sure not the best solution, but it works
List<string> search = new List<string>();
List<string> listBoxItems = new List<string>();
listBoxItems = listBox1.Items.Cast<string>().ToList();
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(textBox1.Text))
{
search.Clear();
listBoxItems.ForEach(x =>
{
if (IsSubstring(textBox1.Text, x))
{
search.Add(x);
}
});
listBox1.DataSource = null;
listBox1.DataSource = search;
}
else
{
listBox1.DataSource = listBoxItems;
}
}
public bool IsSubstring(string text, string x)
{
if (x.ToLower().Contains(text.ToLower()))
{
return true;
}
else
{
return false;
}
}
Upvotes: 0
Reputation: 1074
From the details of FindString,
Finds the first item in the System.Windows.Forms.ListBox that starts with the specified string.
So you will have to custom write code to achieve it. Something like below,
private void textBox1_TextChanged(object sender, EventArgs e)
{
string myString = textBox1.Text;
bool found = false;
for (int i = 0; i <= listBox1.Items.Count - 1; i++)
{
if(listBox1.Items[i].ToString().Contains(myString))
{
listBox1.SetSelected(i, true);
found = true;
break;
}
}
if(!found)
{
MessageBox.Show("Item not found!");
}
}
Upvotes: 6
Reputation: 786
Use StartsWith method to check if specific item starts with string you have entered:
private void searchBox_TextChanged(object sender, EventArgs e)
{
string prefix = searchBox.Text;
bool found = false;
for(int i = 0; i < listBox.Items.Count; i++)
{
if(listBox.Items[i].ToString().StartsWith(prefix))
{
listBox.SelectedItem = listBox.Items[i];
found = true;
break;
}
}
if(!found)
{
MessageBox.Show("Item not found!");
}
}
Upvotes: 3