如何使用从数据库传入的null

时间:2013-12-14 06:41:50

标签: c# database

我收到此错误

  

无法在空值

上调用此方法或属性

在这一行id = rd.GetString(0);上。怎么解决?

public string MaxId()
{
    string id = "";

    con.Open();
    string sql = "SELECT MAX(id) FROM Customer";
    SqlCommand cmd = new SqlCommand(sql, con);
    SqlDataReader rd = cmd.ExecuteReader();
    while (rd.Read()){
        id = rd.GetString(0);
    }
    con.Close();
    return id;
}

1 个答案:

答案 0 :(得分:3)

添加此

!rd.IsDBNull(0)

之前

id = rd.GetString(0);

因此,您的代码看起来像

public string MaxId()

    {
    string id = "";

    con.Open();
    string sql = "SELECT MAX(id) FROM Customer";
    SqlCommand cmd = new SqlCommand(sql, con);
    SqlDataReader rd = cmd.ExecuteReader();
    while (rd.Read())

    {
        if(!rd.IsDBNull(0))
            id = rd.GetString(0);
    }
    con.Close();
    return id;