0

specified cast is not valid在尝试autocompletedatagridviewtextboxcell.. 执行此操作时遇到此错误。我附上了代码的快照以及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;
    }

DataGridView 文本框单元格自动完成代码

堆栈跟踪

4

2 回答 2

1

正如 decyclone 在此线程问题中所建议的那样,在 TextBox 的 AutoComplete 代码中面临问题,在新解决方案中创建一个新的 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用 a替换ComboBox并将其设置DropDownStyleDropDown

于 2012-10-16T08:27:11.603 回答
1

我自己弄清楚了这个问题。我试图做的形式Datagridview AutocompleteChild Form. 我上面发布的代码在new Form. 所以我打开了Child Form一个新的Thread并尝试运行代码并且它有效!感谢您对@chridam 的所有帮助。

于 2012-10-16T09:53:31.180 回答