如何解决单击 datagridview 上的错误列时无法投射错误
我在 Windows 窗体中有一个数据网格,有 3 列。一种是按钮类型,应该是可点击的,并且确实有效。但是,如果我错误地单击了其他 2 列,则会出现如下所述的异常错误。我理解这个错误,因为我的意图是将单击的单元格 Button 转换为相同类型的局部变量。我想知道的是如何防止点击另外两列时出现异常。
代码如下:
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();
};
这里是错误:
> 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)
谢谢, 克里斯
解决方法
来自:How to handle click event in Button Column in Datagridview?
我认为这就是答案。如果有更好的方法,请告诉我。
if (e->ColumnIndex == dataGridView19->Columns["dataGridViewButtonColumn7"]->Index && e->RowIndex >= 0) {
DataGridViewButtonCell^ cell = (DataGridViewButtonCell^)dataGridView19->CurrentCell;
Console::WriteLine("Speaking ");
SimVoice[Convert::ToInt16(dataGridView19->CurrentRow->Cells["dataGridViewTextBoxColumn33"]->Value)]->speak();
//Console::WriteLine("Button on row {0} clicked",e->RowIndex);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。