简体   繁体   中英

How to return default value when value is null or empty

How can I make the below code return zero if the returned value is null or empty. Also how can I return only the first record on the data table

  private DataTable GetData(SqlCommand cmd)
        {
            gridoutofstock.DataBind();
            DataTable dt = new DataTable();
            String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["AhlhaGowConnString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                sda.Dispose();
                con.Dispose();
            }
        }

You need to use SqlCommand.ExecuteScalar instead of the SqlDataAdapter, you are trying to retrive a single scalar value and not a DataSet.

Example :

static int GetOrderQuantity()
        {
            int quantity = 0;
            string sql = "select sum(Quantity) from [dbo].Orderdetails ";
            using (SqlConnection conn = new SqlConnection("Your connection string"))
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    quantity = (int)cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    //Handle exception
                }
            }
            return quantity;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM