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上

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章