Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 值为null或空时如何返回默认值_C#_Sqldataadapter - Fatal编程技术网

C# 值为null或空时如何返回默认值

C# 值为null或空时如何返回默认值,c#,sqldataadapter,C#,Sqldataadapter,如果返回值为null或空,如何使下面的代码返回零。另外,如何仅返回数据表上的第一条记录 private DataTable GetData(SqlCommand cmd) { gridoutofstock.DataBind(); DataTable dt = new DataTable(); String strConnString = System.Configuration.Configuration

如果返回值为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();
            }
        }

您需要使用SqlCommand.ExecuteScalar而不是SqlDataAdapter,因为您尝试检索的是单个标量值,而不是数据集

例如:

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

返回
0
?您的函数被定义为返回一个
数据表
-您不能返回
0
。您可能应该添加更多详细信息或澄清您的问题。这是我的sql命令,它只从[dbo]中返回一个值select sum(Quantity)。Orderdetails那么用什么来代替数据表?请用详细信息编辑您的问题,不要将其添加为注释-这些可能会被读者忽略。听起来像是您在问“为什么我在需要
int
时使用
DataTable
作为返回类型”-这有点难以解释…也许您正在寻找?