对象引用未设置为linq to sql中对象的实例

时间:2013-09-07 18:05:59

标签: c# linq-to-sql datagridview nullreferenceexception

运行以下代码时,我得到异常“System.Nullreferenceexception:对象引用未设置为对象的实例”。我相信它没有初始化allStudents变量,但我不确定allStudents是什么类型。

感谢任何帮助

    private void showStudents(string c)
    {
        try
        {
            using (SMDataClassesDataContext db = new SMDataClassesDataContext())
            {

                var allStudents = from t in db.tbl_students
                                  where t.current_class == c
                                  select t;
              dgViewStudents.ItemsSource = allStudents;
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

2 个答案:

答案 0 :(得分:1)

我设法解决了这个问题。添加空值检查解决了这样的问题:

   if (dgViewStudents != null)
                    dgViewStudents.ItemsSource = allStudents.ToList();

答案 1 :(得分:0)

您需要强制对查询进行评估并将其设置为DataGridView的DataSource ....假设dgViewStudents变量本身不为null并且allStudents查询带回结果,我认为这应该可行。< / p>

var bindingSource = new BindingSource();
var allStudents = from t in db.tbl_students
                  where t.current_class == c
                  select t;
bindingSource.DataSource = allStudents.ToList();
dgViewStudents.DataSource = bindingSource;