-2

I want to do auto generate the value of a field which type is int. Below is my code and it works successfully when I entry one column data manually in database.

But when the DB is totally empty then the output of this query is 'null'. I want when the output of this query is 'null' then the value of createCode will be 0 (zero).

ConnectionObj.Open();
string query = "SELECT MAX(t_code) FROM teacher_table";
CommandObj.CommandText = query;
int createCode = Convert.ToInt32(CommandObj.ExecuteScalar());
if (createCode == 'null')  //can't compare string and int  
{
    createCode = 0;
    return createCode;
}
else
{
    return createCode;
} 

How I can do it?

Habib
  • 219,104
  • 29
  • 407
  • 436
Ikr
  • 43
  • 8

4 Answers4

1

You need to check for DBNull.Value before casting it to an int:

ConnectionObj.Open();
string query = "SELECT MAX(t_code) FROM teacher_table";
CommandObj.CommandText = query;
object code = CommandObj.ExecuteScalar();
if (code == DBNull.Value)
{
    return 0;
}

return Convert.ToInt32(code);
Danny
  • 1,740
  • 3
  • 22
  • 32
1

In Mysql, you can use IFNULL() like this:

string query = "SELECT IFNULL(MAX(t_code),0) FROM teacher_table";

In Sql Server you can use ISNULL() like this:

  string query = "SELECT ISNULL(MAX(t_code),0) FROM teacher_table";
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Change if (createCode == 'null') to if (createCode == DBNull.Value).

rory.ap
  • 34,009
  • 10
  • 83
  • 174
0

Use:

object obj = CommandObj.ExecuteScalar();
if (obj == null || obj == DBNull.Value)
    return 0;
else
    return Convert.ToInt32(obj);

Since your createCode is of type int, it can never be null, instead your current code will not even compile.

user2711965
  • 1,795
  • 2
  • 14
  • 34