Object Cannot Be Assigned To Other Types From DBNull
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.'
Solution 1:
jdweng suggestion in comment is working:
var results = (cmd.ExecuteScalar() == DBNull.Value) ? null : cmd.ExecuteScalar();
Solution 2:
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.
Solution 3:
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();
Post a Comment for "Object Cannot Be Assigned To Other Types From DBNull"