当表中没有值时,我们如何从表中获取空值

时间:2014-04-16 04:46:52

标签: c# sql-server

try
{
    conn.Open();
    string query = "SELECT IGP_CODE FROM TBL_IGP_HEADER";
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.ExecuteNonQuery();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    int value = (int)dt.Rows[0]["IGP_CODE"];
    if (value==null)
    {
        string myquery = "SELECT ISNULL(IGP_CODE,O) AS 'IGP_CODE' FROM TBL_IGP_HEADER";
        SqlCommand comd = new SqlCommand(myquery, conn);
        comd.ExecuteNonQuery();
        SqlDataReader dr = comd.ExecuteReader();
        dr.Read();
        int values = Convert.ToInt32(dr["IGP_CODE"]);
        textIGPNo.Text = values.ToString();
    }
    else
    {
        MessageBox.Show("Test");
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
textIGPDate.Text = DateTime.Now.ToShortDateString();
textIGPTime.Text = DateTime.Now.ToShortTimeString();

3 个答案:

答案 0 :(得分:0)

由于您已将变量Value初始化为Int,因此无法保持Null。它将默认初始化为0。 你可以检查dt.Rows == 0

答案 1 :(得分:0)

如果您要检查空值,请尝试使用

if(dt.Rows[0]["IGP_CODE"] == DBNull.Value)
{
    //your code goes here
}
else
{  
    //your code goes here
}

如果你必须在变量中存储该列的值,请尝试使用可空类型,因为int无法处理空值

int? value = dt.Rows[0]["IGP_CODE"] as int?

答案 2 :(得分:0)

 try
        {
            conn.Open();

            string myquery = "SELECT ISNULL(IGP_CODE,0) FROM TBL_IGP_HEADER";
            SqlCommand comd = new SqlCommand(myquery, conn);
            comd.ExecuteScalar();
            SqlDataAdapter da = new SqlDataAdapter(comd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            string values = dt.Rows.Count.ToString();
            if (values == null)
            {
                textIGPNo.Text = values;
            }
            else
            {
                string myquery1 = "SELECT IGP_CODE FROM TBL_IGP_HEADER";
                SqlCommand cmd = new SqlCommand(myquery1, conn);
                cmd.ExecuteNonQuery();
                SqlDataAdapter daa = new SqlDataAdapter(cmd);
                DataTable dts = new DataTable();
                daa.Fill(dts);
                int value = dt.Rows.Count;
                int nvalue = value + 1;
                textIGPNo.Text = nvalue.ToString();
            }
       }
   catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }