对象引用未设置为 linq to SQL 中的对象实例
本文关键字:对象 实例 SQL to 设置 linq 对象引用 | 更新日期: 2023-09-27 18:30:28
运行以下代码时,我得到异常"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());
}
}
我设法解决了这个问题。添加对空值的检查解决了这样的问题:
if (dgViewStudents != null)
dgViewStudents.ItemsSource = allStudents.ToList();
您需要强制计算查询并将其设置为DataGridView的数据源。假设 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;