在 CellValidating 事件中比較舊值與新值:
If e.RowIndex >= 0 And IIf(IsDBNull(DataGridView2.CurrentCell.Value), "", DataGridView2.CurrentCell.Value) <> e.FormattedValue Then ...
刪除數值型欄位內容時,e.FormattedValue 為空字串 "",嘗試與 Double 比較拋出 InvalidCastException: 從字串 "" 轉換為 Double 無效。
e.FormattedValue 型別為 Object,實際為 String (空字串)。當另一邊運算元為數值型別 (Double) 時,VB.NET 嘗試隱式轉換字串為 Double 失敗。
If e.RowIndex >= 0 AndAlso _
IIf(IsDBNull(DataGridView2.CurrentCell.Value), "", DataGridView2.CurrentCell.Value).ToString() <> _
e.FormattedValue.ToString() Then
' 驗證邏輯...
End If
.ToString(),確保均為 String 型別,避免隱式轉換。AndAlso 短路評估,提升效能並避免 NullReferenceException。e.FormattedValue 永遠不為 Nothing (至少為 String.Empty),安全呼叫 .ToString()。CellParsing:在使用者輸入提交前轉換格式,可將空字串轉為 DBNull.Value 或 0。DefaultValuesNeeded:新增列時預設數值欄位為 0,避免空值驗證問題。將比較雙方統一轉為 String (.ToString()) 即可解決刪除數值儲存格時的型別轉換錯誤,並建議改用 AndAlso 提高健壯性。