我在为specified cast is not valid
尝试autocomplete
时遇到此错误datagridviewtextboxcell
。我附上了代码的快照以及stack trace
。我错过了什么吗?
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox prodCode = e.Control as TextBox;
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
var source = new AutoCompleteStringCollection();
String[] stringArray = newDB.CustomerTbls.Where(s => s.Status == "Active" & s.Type == "Customer").Select(s => s.Name).ToArray<string>();
source.AddRange(stringArray);
if (prodCode != null)
{
prodCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
prodCode.AutoCompleteCustomSource = source;
prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}
else
prodCode.AutoCompleteCustomSource = null;
}
答案 0 :(得分:1)
正如此线程Problem faced in AutoComplete code for TextBox 中的decyclone所建议的,在新解决方案中创建一个新的Windows应用程序项目,创建一个新表单并使用该表单尝试以下代码,即创建一个String[]
的DataTable
行计数的大小,然后将其添加到AutoCompleteStringCollection
对象
AutoCompleteStringCollection data = new AutoCompleteStringCollection ();
data.AddRange(new string[]
{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
});
// Create and initialize the text box
var prodCode = new TextBox
{
AutoCompleteCustomSource = data,
AutoCompleteMode = AutoCompleteMode.SuggestAppend,
AutoCompleteSource = AutoCompleteSource.CustomSource,
Location = new Point(20, 20),
Width = ClientRectangle.Width - 40,
Visible = true
};
看看它是否有效。如果它不起作用,那么您可以尝试本文AutoCompleteCustomSource – Specified Cast is Not Valid 中概述的替代解决方案,即将TextBox
替换为ComboBox
并将其DropDownStyle
设置为{{ 1}}。
答案 1 :(得分:1)
我自己想出了这个问题。我尝试Datagridview Autocomplete
的形式是Child Form
。我上面发布的代码是new Form
。所以我打开了Child Form
作为一个新的Thread
,并尝试运行代码,它工作了!! Thanx为你所有的帮助@chridam。