简体   繁体   中英

Dotnet :- How to make Autocomplete textbox search case insensitive?

I am able to implement the autocomplete textbox search, but its case sensitive. i want to make it sase insensitive. I have put an or condition but it checks for first entered letter only. i want the search to be fully case insensitive.

Below is my code

public partial class Form1 : Form
{
    AutoCompleteStringCollection acsc;
    public Form1()
    {
        InitializeComponent();
         acsc = new AutoCompleteStringCollection(); 
        textBox1.AutoCompleteCustomSource = acsc; 
        textBox1.AutoCompleteMode = AutoCompleteMode.None; 
        textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        acsc.Add("Sim Vodafone");
        acsc.Add("sim vodafone");
        acsc.Add("sIm");
        acsc.Add("siM"); 
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string d = null;

        listBox1.Items.Clear(); 
        if (textBox1.Text.Length == 0) 
        { 
            hideResults(); 
            return; 
        } 
        foreach (String s in textBox1.AutoCompleteCustomSource) 
        {
            d = textBox1.Text.ToUpper();
            if (s.Contains(d) || s.Contains(textBox1.Text)) 
            { 
                Console.WriteLine("Found text in: " + s); 
                listBox1.Items.Add(s); 
                listBox1.Visible = true; 
            } 
        } 
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        textBox1.Text = listBox1.Items[listBox1.SelectedIndex].ToString(); 
        hideResults(); 
    }

            void listBox1_LostFocus(object sender, System.EventArgs e) 
    { 
        hideResults(); 
    }  

    void hideResults() 
    { 
        listBox1.Visible = false; 
    }
}

}

I think the only thing, that's missing to convert the string in you autoCompleteSource to upper. Change

d = textBox1.Text.ToUpper();
if (s.Contains(d) || s.Contains(textBox1.Text)) 
{ 
     Console.WriteLine("Found text in: " + s); 
     listBox1.Items.Add(s); 
     listBox1.Visible = true; 
}

to

d = textBox1.Text.ToUpper();
string upperS = s.ToUpper();
if (upperS.Contains(d)) 
{ 
     Console.WriteLine("Found text in: " + s); 
     listBox1.Items.Add(s); 
     listBox1.Visible = true; 
}

and it should work. Although I am sure, that there should be a simplier solution to autocomplete, than creating your own listbox.

Can you try this.

  d = textBox1.Text;
  if (s.Contains(d.ToUpper()) || s.Contains(d.ToLower()) || s.Contains(textBox1.Text.ToUpper()) || Contains(textBox1.Text.ToLower())) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM