C#.net出错,不知道错在哪?

来源:百度知道 编辑:UC知道 时间:2024/05/22 08:35:26
SqlConnection sqlcon=new SqlConnection("server=.;uid=sa;pwd=;database=SMessagedatabase");
sqlcon.Open();
SqlCommand cmd=new SqlCommand();
cmd.CommandText="select count(*) from student where xueyuan='"+departtv.SelectedNode.Parent.ToString()+"'";//出错.
cmd.Connection=sqlcon;
int count=Convert.ToInt32(cmd.ExecuteScalar());
这里是程序片断,运行时出错:

未处理的“System.NullReferenceException”类型的异常出现在 StudentMessageSys.exe 中。

其他信息: 未将对象引用设置到对象的实例。

程序“[4084] StudentMessageSys.exe”已退出,返回值为 0 (0x0)。

请高手帮帮忙,帮我找出错在哪?

departtv.SelectedNode.Parent.ToString()+"'";//出错.

如果是上面这句话出错的话,应该是这个时候departtv里面没有选中的节点。所以departtv.SelectedNode为null值,就会报这个错。
报这个错误的另外一种是这个对象未初始化。