cast null value from database

Viewed 11

I have a form that takes data from a database, I want to convert the data from null to a value of 0 in case there is no row in the database, I tried a lot but did not find the solution

{
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select max(Inv_no) from Tb_agentSales";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter ds = new SqlDataAdapter(cmd);
        ds.Fill(dt);
                   
        if (dt.Rows.Count > 0 )
        {
            double result = (Convert.ToDouble(cmd.ExecuteScalar()) +1);
            textBox23.Text = result.ToString();
        }
     

        con.Close();

    }
1 Answers
{
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select max(Inv_no) from Tb_agentSales";
    cmd.ExecuteNonQuery();
    DataTable dt = new DataTable();
    SqlDataAdapter ds = new SqlDataAdapter(cmd);
    ds.Fill(dt);

    double result;         
    if (dt.Rows.Count > 0)
    {
        result = (Convert.ToDouble(cmd.ExecuteScalar()) + 1);
        textBox23.Text = result.ToString();
    }
    else {
        result = 0;
    }
    

    con.Close();

}

This should work, be aware that I haven't tested it though.

Related