c# - 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
解决方案
您的代码应该可以正常工作。我在一个小型 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);
}
}
推荐阅读
- python - 根据用户的时区显示 Django Admin DateTimeField
- c# - 在 F# 中使用可为空的引用类型
- java - 如何在自定义注释中获取默认消息中的字段名称?
- database - MongoDB——单个字段的 TTL / 过期?
- javascript - 五个输入取决于两个选择的值
- xaml - 如何为标签文本添加边框/轮廓?
- javascript - 最后创建带有按钮的平面列表的最佳方法是什么?用 Firebase 反应本机
- python - 按允许的列值组合列表过滤 df
- go - K8s中如何根据与pod的交互获取用户的ip
- flutter - 在 Flutter 中保存抽屉的状态