System.InvalidCastException: Object cannot be cast from DBNull to other types
c#, oracle
Solution
As the error message says, the value of the cell is `DBNull.Value` and it can't convert from that to whatever you want it to be (in this case a `long` or an `int`). You need to check for `DBNull` before converting/casting the number:
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);
Because this adds some annoying overhead, if you do this much you'll probably want to make a helper method that does it for you.
public static long? getLongFromDB(object value)
{
if (value == DBNull.Value) return null;
return Convert.ToInt64(value);
}
Then your code can be:
Int64 id_riga = getLongFromDB((sender as DataGridView).Rows[e.RowIndex].Cells["column_ID"].Value)
.GetValueOrDefault();
Problem
I have an exception in my code. I have already tried to change my int64 to int32 but that doesn't change it. In the database, the cells that represent "column_ID" have datatype NUMBER. The problem is at line 7 in this code: ``` 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(); } } ``` the error is: ``` 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) ``` Can someone help me resolve this?