我的代码中有一个异常。我已经尝试将我的 int64 更改为 int32,但这并没有改变它。
在数据库中,表示“column_ID”的单元格的数据类型为 NUMBER。
问题出在这段代码的第 7 行:
private void dataGridView_ArticleINVIA_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.RowIndex <= (sender as DataGridView).Rows.Count - 1)
{
try
{
Int64 id_riga = Convert.ToInt64((sender as DataGridView).Rows[e.RowIndex].Cells["column_ID"].Value);
//Exception thrown here:
int id_macchina = Convert.ToInt32((sender as
DataGridView).Rows[e.RowIndex].Cells["column_Machine"].Value);
FormRecipeNote PopUpNote = new FormRecipeNote(id_macchina,
"MODIFICA", id_riga, 0);
PopUpNote.ShowDialog(this);
PopUpNote.Dispose();
}
catch (Exception Exc)
{
FormMain.loggerSoftwareClient.Trace(this.Name + " " + Exc);
}
//DataGrid_ArticleINVIA();
}
}
错误是:
System.InvalidCastException: Object cannot be cast from DBNull to other types.
at System.DBNull.System.IConvertible.ToInt64(IFormatProvider provider)
at System.Convert.ToInt64(Object value)
at Software_Client.FormSendReceiveRecipe.dataGridView_ArticleINVIA_CellDoubleClick(Object sender, DataGridViewCellEventArgs e)
谁能帮我解决这个问题?
最佳答案
如错误消息所述,单元格的值为 DBNull.Value
并且无法将其转换为您想要的任何值(在本例中为 long
或 int
)。在转换/转换数字之前,您需要检查 DBNull
:
Int64 id_riga = 0;
object value = (sender as DataGridView).Rows[e.RowIndex].Cells["column_ID"].Value;
if(value != DBNull.Value)
id_riga = Convert.ToInt64(value);
因为这会增加一些恼人的开销,如果你做了这么多,你可能想要制作一个帮助方法来为你做这件事。
public static long? getLongFromDB(object value)
{
if (value == DBNull.Value) return null;
return Convert.ToInt64(value);
}
那么你的代码可以是:
Int64 id_riga = getLongFromDB((sender as DataGridView).Rows[e.RowIndex].Cells["column_ID"].Value)
.GetValueOrDefault();
关于c# - 系统.InvalidCastException : Object cannot be cast from DBNull to other types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14058745/