greg
greg

Reputation: 337

What am i doing wrong? And what should i be doing differently? (Auto complete winforms textbox)

c# winform

I have read multiple articles/suggestions on how to do this, and below is one of the few I have tried, but it's not working. In fact, when user types into the textbox, nothing happens.

private void OperationListForm_Load(object sender, EventArgs e)
    {
        AutoCompleteStringCollection textBoxCollection = new AutoCompleteStringCollection();

        foreach (var item in _oiList)  //_oiList is a list of objects 
        {
            textBoxCollection.Add(item.ToString());
        }

        textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
        textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
        textBox1.AutoCompleteCustomSource = textBoxCollection;
    }

I'm new so, If I need to provide more info, please let me know.

Upvotes: 0

Views: 67

Answers (2)

hcham1
hcham1

Reputation: 1847

A few things you need to double check:

  • Make sure that textBoxCollection has valid items in it
  • Make sure that your 'OperationListForm_Load' method is being called by setting a breakpoint and running your application
  • Make sure your textBox1 is added to the form properly

I tested your code and it works for me. This is what I did to check:

  1. Created a new Windows Form project
  2. Added a Text Box to the form
  3. Added the following code to the Form1.cs:

    public partial class Form1 : Form
    {
      public Form1()
      {
        InitializeComponent();
        InitTextBox();
      }
    
      void InitTextBox()
      {
         AutoCompleteStringCollection textBoxCollection = new AutoCompleteStringCollection();
         textBoxCollection.Add("Bobby");
         textBoxCollection.Add("Billy");
         textBoxCollection.Add("Britney");
    
         textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
         textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
         textBox1.AutoCompleteCustomSource = textBoxCollection;
      }
    }
    

and here is a screenshot of this working:

screenshot of working code

Upvotes: 2

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

First you must create array and add it to AutoCompleteStringCollection, next set it as data source. You can do it like my sample, its working. Your problem is with your datasource which you try add. It's list of object you cant do that.

AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection();
String[] yourArray = new[] {"Cat", "Car", "Dog", "Dinner", "War", "White"};
stringCollection.AddRange(yourArray);
textBox1.AutoCompleteCustomSource = stringCollection;
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

enter image description here

Upvotes: 0

Related Questions