我收到此错误
无法在空值
上调用此方法或属性
在这一行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;
}
答案 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;