【问题标题】:Unable to cast error when clicking on wrong column on datagridview单击 datagridview 上的错误列时无法转换错误
【发布时间】:2021-08-22 01:14:13
【问题描述】:

我在 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)

谢谢, 克里斯

【问题讨论】:

  • 在进行演员表之前测试它是否是正确的类型。我不知道 CLI 语法,但现代 C# 方式是if (dataGridView19.CurrentCell is DataGridViewButtonCell btn) {btn.DoSomething(); }。您可能希望将此问题标记为winforms,以便更多地接触 WinForms 人
  • 在网格中CellContentClick 传入的变量...DataGridViewCellEventArgs e 具有识别“哪个”列被单击的属性...e.ColumnIndex...在投射单元格之前检查此值,如果@987654328 @=按钮栏,则施法成功。如果e.ColumnIndex != 按钮列,则不要投射单元格并直接忽略它。

标签: c# winforms c++-cli


【解决方案1】:

发件人: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);
    }

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多