I have a datagrid in Windows Forms and there are 3 columns. One is a button type and should be clickable and that does work. However, if I mistakenly click on the other 2 columns, I get an exception error as stated below. I understand the error because my intent was to cast the clicked cell Button to a local variable of the same type. What I want to know is how to prevent the exception when I click on the other two columns.
Here is the code:
private: System::Void dataGridView19_CellContentClick(System::Object^ sender,
System::Windows::Forms::DataGridViewCellEventArgs^ e) {
DataGridViewButtonCell^ cell = (DataGridViewButtonCell^)dataGridView19->CurrentCell;
Console::WriteLine("Speaking ");
SimVoice[Convert::ToInt16(dataGridView19->CurrentRow->Cells["dataGridViewTextBoxColumn33"]->Value)]->speak();
};
And here is the error:
> System.InvalidCastException: Unable to cast object of type
'System.Windows.Forms.DataGridViewTextBoxCell' to type
'System.Windows.Forms.DataGridViewButtonCell'.
at CppCLRWinformsProjekt.Form1.dataGridView19_CellContentClick(Object sender,
DataGridViewCellEventArgs e) in F:\WindowsProjects\CppCLR_WinformsP3-V1 -
7\CppCLR_WinformsProjekt3\Form1.h:line 2785
at
System.Windows.Forms.DataGridView.OnCellContentClick(DataGridViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnCommonCellContentClick(Int32 columnIndex, Int32 rowIndex, Boolean doubleClick)
at
System.Windows.Forms.DataGridViewCell.OnMouseUpInternal(DataGridViewCellMouseEventArgs e)
at System.Windows.Forms.DataGridView.OnCellMouseUp(DataGridViewCellMouseEventArgs e)
at System.Windows.Forms.DataGridView.OnMouseUp(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Thanks, Chris