Reputation: 219
I have this error specified cast is not valid
while trying to do autocomplete
for datagridviewtextboxcell
.. I have attached a snapshot of the code along with the stack trace
. Am i missing something here??
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;
}
Upvotes: 0
Views: 1483
Reputation: 219
I figured out the issue myself. The form in which i was trying to do Datagridview Autocomplete
was a Child Form
. And the code which I posted above was working in a new Form
. So i opened the Child Form
as a new Thread
and tried running the code and it worked!! Thanx for all your help @chridam.
Upvotes: 1
Reputation: 103375
As suggested by decyclone in this thread Problem faced in AutoComplete code for TextBox , create a new Windows Application project in a new solution, create a new Form and try the following code with that form, i.e. create a String[]
of the size of the DataTable
row count and then add it to the AutoCompleteStringCollection
object
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
};
See if it works or not. If it doesn't work then you can try an alternative solution as outlined in this article AutoCompleteCustomSource – Specified Cast is Not Valid , i.e. replace the TextBox
with a ComboBox
and set its DropDownStyle
to DropDown
.
Upvotes: 1