Casting error in my form
I have a ComboBox
in a DataGridView
. However I get an error when I run it:
Unable to cast object of type 'System.Windows.Forms.DataGridView' to type 'System.Windows.Forms.ComboBox'.
What can I do to resolve this error?
ComboBox comboBox;
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox)
{
comboBox = e.Control as ComboBox;
if (dataGridView1.CurrentCell.ColumnIndex >= 0)
{
System.Diagnostics.Debug.WriteLine("Edit Control Showing");
comboBox.SelectedIndexChanged -= new EventHandler(comboBoxItems_SelectedIndexChanged);
comboBox.SelectedIndexChanged += new EventHandler(comboBoxItems_SelectedIndexChanged);
}
}
}
void comboBoxItems_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int comboBoxSelectedIndex = ((ComboBox)sender).SelectedIndex;
string comboboxSelectedValue = ((ComboBox)sender).SelectedText;
int gridViewSelectedRow = dataGridView1.CurrentRow.Index;
if (comboBoxSelec开发者_如何学JAVAtedIndex >= 0 && gridViewSelectedRow >= 0)
{
System.Diagnostics.Debug.WriteLine("ComboBox Index - " + comboBoxSelectedIndex);
System.Diagnostics.Debug.WriteLine("GridView Index - " + gridViewSelectedRow);
if (comboBox != null)
{
comboBox.SelectedIndexChanged -= new EventHandler(comboBoxItems_SelectedIndexChanged);
}
}
}
catch(Exception E)
{
}
}
Looks like this method is also registered to an event of type DataGridView
. That is why when you try to cast it (sender) to ComboBox
, it throws an exception. Because, in that case, sender is of type DataGridView
.
I would also recommend checking the sender
object before attempting to cast it (would confirm what decyclone mentioned in his answer in addition to preventing casting errors):
if(sender is ComboxBox) {
//cast
}
I think somehow you have set the comboBoxItems_SelectedIndexChanged event handler to the DataGridView itself. Check the properties window of DataGridView and if it's there, remove it. Also I recommend using "as" keyword for casting and checking it for "null".
精彩评论