AutoCompleteCustomSource – Specified Cast is Not Valid

There was a requirement to implement a textbox with a databound AutoComple feature. As the Autocomplete source was a database, I have to go for a custom DataSource.

The main requirements for an auto-complete textbox (in this scenario) are:

  • AutoCompleteMode is set to Suggest(or SuggestAppend).
  • AutoCompleteSource is set to CustomSource
  • AutoCompleteCustomSource is set AutoCompleteStringCollection.

A sample code for this: (source)

namespace AutoCompleteTextBox
{
   public partial class frmAuto : Form
   {
      public string strConnection = 
             ConfigurationManager.AppSettings["ConnString"];
      AutoCompleteStringCollection namesCollection = 
             new AutoCompleteStringCollection();

      public frmAuto()
      {
         InitializeComponent();
      }

      private void frmAuto_Load(object sender, EventArgs e)
      {
         SqlDataReader dReader;
         SqlConnection conn = new SqlConnection();
         conn.ConnectionString = strConnection;
         SqlCommand cmd = new SqlCommand();
         cmd.Connection = conn;
         cmd.CommandType = CommandType.Text;
         cmd.CommandText = "Select distinct [Name] from [Names] order by [Name] asc";
         conn.Open();
         dReader = cmd.ExecuteReader();

         if (dReader.HasRows == true)
         {
            while (dReader.Read())
               namesCollection.Add(dReader["Name"].ToString());
         }
         else
         {
             MessageBox.Show("Data not found");
         }
         dReader.Close();

         txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
         txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
         txtName.AutoCompleteCustomSource = namesCollection;
      }

      private void btnCancel_Click(object sender, EventArgs e)
      {
         Application.Exit();
      }
      private void btnOk_Click(object sender, EventArgs e)
      {
         MessageBox.Show("Hope you like this example");
      }
   }
}

I implemented the above properties and other related coding. The build was okay but when I executed the application, I got a Specified Cast is Not Valid exception.

I thought that I made some mistake while implementing, I revised the code and could not find anything wrong. The error was still there! I googled and came to know that I am not alone with this exception. I got a different implementation from MSDN for loading to the custom source.

AutoCompleteStringCollection source = new AutoCompleteStringCollection ();
source.AddRange(new string[]
   {
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December"
   });

// Create and initialize the text box
var textBox = new TextBox
{
   AutoCompleteCustomSource = source,
   AutoCompleteMode = AutoCompleteMode.SuggestAppend,
   AutoCompleteSource = AutoCompleteSource.CustomSource,
   Location = new Point(20, 20),
   Width = ClientRectangle.Width - 40,
   Visible = true
};

I created a String[] of the size of the DataTable row count and then added it to the AutoCompleteStringCollection object (similar to the above code). On executing the application, the result was same.

As I placed the code in the middle of my application, to avoid any confusion, I added a new windows form and updated my Program.cs to start from that form. On executing the application, the same error was there to greet me. I even tried to replace my DataBound source with the above static code, but no way. A simple thing that was supposed to be done in less than 30 min took hours of my time, still unsolved.

Since my Program.cs was having a lot of startup configurations and checks, for a final test I created a new WindowsFormApplication Project and used the MSDN code in the FormLoad event. On executing the application, surprisingly it executed normally giving the desired results. This was totally a wired situation. Most of the times, we are worried when something does not work properly BUT some other times, we are worried when some thing works. It was one of those rare cases.

Upon further googling, I came to know that it has surprisingly something to do with the STAThread attribute. In my application, I am having different forms being executed in different threads so I have removed the STAThread. It was not possible to apply the attribute in my application. It revealed that this thing has been reported to Microsoft as a BUG in Visual Studio 2005 in 2004 and separately 2007. If you happen to get the same scenario, please rate this issues and post your comments to ask Microsoft from wake up from a 7+ year long sleep.

To get the thing done, I have to go for the alternative solution. I replaced the TextBox with a ComboBox and set its DropDownStyle to DropDown. It was not EXACTLY same as the desired output but still usable.

2 thoughts on “AutoCompleteCustomSource – Specified Cast is Not Valid

Leave a Comment