2

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();
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
kozyalcin
  • 83
  • 10
  • Sorry. What is the error message you are getting? Please edit your question and add the exact text of the error message. – RyanNerd Sep 08 '19 at 10:52
  • If there is no data, `Min(...)` and `Max(...) ` return the value DBNull. You have to check for such NULL values before handing the result to `Convert.ToInt32` – Klaus Gütter Sep 08 '19 at 10:53
  • Cast DBNull to null. So try something like this : var results = (cmd.ExecuteScalar == DBNull.Value) ? null : cmd.ExecuteScalar – jdweng Sep 08 '19 at 12:45
  • Yes it work. Thanks @jdweng var results = (cmd.ExecuteScalar() == DBNull.Value) ? null : cmd.ExecuteScalar(); – kozyalcin Sep 09 '19 at 13:00

3 Answers3

1

jdweng suggestion in comment is working:

var results = (cmd.ExecuteScalar() == DBNull.Value) ? null : cmd.ExecuteScalar();
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
kozyalcin
  • 83
  • 10
  • This executes the command twice, not a good practice, spacially if the command writes data. Consider placing the output of `cmd.ExecuteScalar()` in a variable. – Jonathan Larouche Sep 25 '19 at 22:02
0

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.

Mojtaba Nava
  • 858
  • 7
  • 17
0

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();