Object cannot be assigned to other types from DBNull

320 Views Asked by At

I get minimum number in my database. But when no data in my database I get this error.

System.InvalidCastException: 'The object cannot be assigned to other types from DBNull.'

Code:

SqlCommand cmd = new SqlCommand("SELECT MAX(GidenEvrakSira) FROM GidenEvrak", con);    
SqlCommand smd = new SqlCommand("Select Min(GidenEvrakSira) FROM GidenEvrak Where UserID is null", con);    

con.Open();    

maxnum = Convert.ToInt32(cmd.ExecuteScalar());
minum = Convert.ToInt32(smd.ExecuteScalar());    

con.Close();
3

There are 3 best solutions below

1
kozyalcin On BEST ANSWER

jdweng suggestion in comment is working:

var results = (cmd.ExecuteScalar() == DBNull.Value) ? null : cmd.ExecuteScalar();
1
Mojtaba Nava On

At run-time (tested under ODP.NET but should be the same under any ADO.NET provider), it behaves like this:

If the row does not exist, the result of cmd.ExecuteScalar() is null, which is then casted to a null string and assigned to getusername. If the row exists, but has NULL in username (is this even possible in your DB?), the result of cmd.ExecuteScalar() is DBNull.Value, resulting in an InvalidCastException. In any case, the NullReferenceException should not be possible, so your problem probably lies elsewhere.

0
Jonathan Larouche On

Change your query to always return a value by surrounding the max/min with ISNULL function.

SqlCommand cmd = new SqlCommand("SELECT isnull(MAX(GidenEvrakSira),0) FROM GidenEvrak", con);    
SqlCommand smd = new SqlCommand("Select isnull(Min(GidenEvrakSira),0) FROM GidenEvrak Where UserID is null", con);    

con.Open();    

maxnum = Convert.ToInt32(cmd.ExecuteScalar());
minum = Convert.ToInt32(smd.ExecuteScalar());    

con.Close();