linq读取数据为空时的错误
用linq查询时因为数据表中某一项为空造成:
未将对象引用设置到对象的实例。的错误,如何解决啊
用SQL时,当读取的数据为空时却不会出错
数据表中TeaID=1005 的TeaAge为NULL
protected void Button1_Click(object sender, EventArgs e)
{
sqlconn.Open();
string s = "select * from TeacherInfo where TeaID=1005 ";
SqlCommand cmd = new SqlCommand(s,sqlconn );
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
TextBox1.Text = dr["TeaAge"].ToString();
dr.Close();
sqlconn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
testDataContext test = new testDataContext();
var query = from q in test.TeacherInfo where q.TeaID == 1005 select q;
var result = query.ToArray()[0];
TextBox1.Text = result.TeaAge.ToString ();
}
------解决方案-------------------- Convert.ToString(result.TeaAge)
或result.TeaAge.HasValue先判断下
------解决方案--------------------这是因为 dr["TeaAge"] 的类型是 object,而 result.TeaAge 的类型是 int?。
很简单,写:
C# code
TextBox1.Text = result.TeaAge==null?"null":result.TeaAge.ToString ();