首页 > 解决方案 > C# Specified Cast is Not Valid

问题描述

I want to get autocomplete for text box given in parameter

 public static void GetProductsForTextBox(TextBox MyProductTextBox)
    {
        AutoCompleteStringCollection MyCollection = new   AutoCompleteStringCollection();
        try
        {
            SqlCommand cmd = new SqlCommand("SELECT Title FROM Products", Database.con);
            cmd.CommandType = CommandType.Text;
            Database.con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                 MyCollection.Add(Convert.ToString(reader["Title"].ToString())); 
            }
            reader.Close();
            Database.con.Close();
            MyProductTextBox.AutoCompleteCustomSource = MyCollection;
        }
        catch (InvalidCastException exc)
        { MessageBox.Show(exc.Message); }
        catch (Exception exc)
        { MessageBox.Show(exc.Message); }
        finally
        {   Database.con.Close();  }
    }

Specified Cast is not valid

标签: c#

解决方案


您的代码应该可以正常工作。我在一个小型 WinForms 测试应用程序中尝试了以下操作(有一个名为的表单Form1,只有一个名为 TextBox的表单MyProductTextBox),但我没有遇到任何问题:

private void Form1_Load(object sender, EventArgs e)
{
    AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();

    try
    {
        MyCollection.Add("Foo");
        MyCollection.Add("Bar");

        MyProductTextBox.AutoCompleteCustomSource = MyCollection;

        MyProductTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
        MyProductTextBox.AutoCompleteMode = AutoCompleteMode.Suggest;
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

推荐阅读