1

运行以下代码时,出现异常“System.Nullreferenceexception:object reference not set to an instance of an object”。我相信这与不初始化 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());
        }
    }
4

2 回答 2

1

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

   if (dgViewStudents != null)
                    dgViewStudents.ItemsSource = allStudents.ToList();
于 2013-09-08T09:45:10.153 回答
0

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

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;
于 2013-09-07T18:14:06.607 回答