I am fetching a column from database of char(2) data type.
On an Event, I am changing the char data type to int and incrementing it by 1, with this code:
int i = 0;
using (SqlConnection sqlCon = new SqlConnection(Login.connectionString))
{
string commandString = "SELECT MAX(CAST(Category_Code as INT)) FROM Category;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())
{
i = 1;
if (dr[0] == null)
{
Ctgry_CtgryCodeCb.Text = "1";
}
else
{
int cat_next_code = int.Parse(dr[0].ToString());
Ctgry_CtgryCodeCb.Text = (cat_next_code + 1).ToString();
}
}
}
It is working properly but not for the first time (doesn't add 1 to empty or 0) as column is empty.It shows some error that it is not is correct format to convert. I also set the default value of the column to 0, but it shows ((0)) as default value.
Any help would be appreciated.

If you are using this code to increment primary key value of the database table, you shouldn't be doing this way. You should be using
IDENTITYcolumn feature available in the database.Since you have not explained why you are not using
IDENTITYcolumn, looks like this code is for some other purpose.As per your code you are getting Maximum value of some column from the database and incrementing it by one in the code.
When the table in the database is empty you not get anything is the reader. So While loop will not be executed at all. So even if you are checking for NullOrEmpty inside the while loop, it will never get executed.
Also you don't need to use
SqlDataReaderhere. Since you are returning only one single value from the query you can useExecuteScalarmethod ofSqlCommandand get that value. It will be simpler.My strong recommendation is to use
IDENTITYcolumn instead of doing all this code.This will help you resolve your current issue.
SqlDataReaderis overkill in this case and I don't like to answer for the wrong approach but since you insist consider following.