C# winform單元格的formatted值的類型錯誤 DataGridView中CheckBox列運行時候System.FormatException異常


    在DataGridView手動添加了CheckBox列;在窗體Show的時候,遇到一個錯誤:錯誤如下: 

DataGridView中發生一下異常:System.FormatException:單元格的Formatted值的類型錯誤.要替換此默認對話框,請處理DataError事件.

點擊以后有一對話框錯誤如下:

DataGridView中發生一下異常:

SystemArgumentException:為DataGridViewCheckBoxCell提供的值的類型錯誤.

在System.Windows.Forms.DataGridViewCheckBoxCell.set_EditiingCellFormattedValue(Object value)

在System.Windows.Forms.DataGridView.InitializeEditingCellValue (DataGridViewCessStyle&dataGridViewCellStyle,DataGridViewCell&dataGridViewCell)

要替換此默認對話框,請處理DataError事件.

我之前曾經用過CheckBox列,此次和之前的區別是 AllowUserToAddRows=true;我將該屬性設置為false,錯誤沒有出現,可以確定該錯誤與系統自動添加的行及checBox的默認值為null有關。

我在DefaultValuesNeeded事件中增加了默認值,發現錯誤依舊。

仔細研究發現如下兩種解決方法:

其一:在CellFormatting事件中處理

{

            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "AZK")               {                   if (e.Value == null)                       e.Value = false;               }

}

 

其二:在在CellFormatting事件中不處理,但DataError事件中處理

        {               if (dataGridView1.Rows[e.RowIndex].IsNewRow)                   return;           }

 

Note: DataGridView中幾個事件發生的順序記錄如下,以備查尋

  在AllowUserToAddRows=true時候的事件發生次序

    Form.Show ---> CellFormatting (如果出錯,goto DataError),注意這里的NewRow沒有觸發DefaultValuesNeeded事件。

如果發生其他比如 RowEnter事件

  (DefaultValuesNeeded) ---> RowEnter ---> CellClick

  (DefaultValuesNeeded) ---> RowsAdded ---> UserAddedRow

  DefaultValuesNeeded事件不會發生在 IsNewRow=true的row上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM