如果value为null或为空,如何返回默认值

时间:2015-08-31 21:58:46

标签: c# sqldataadapter

如果返回的值为null或为空,如何使下面的代码返回零。另外,我如何只返回数据表中的第一条记录

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

1 个答案:

答案 0 :(得分:1)

您需要使用SqlCommand.ExecuteScalar而不是SqlDataAdapter,您试图检索单个标量值而不是DataSet。

示例:

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;
        }