我有这段代码填充我的DataGrid
:
private void getData()
{
var context = new dbStudentEntities();
var data = (from s in context.tblStudents
join c in context.tblClasses
on s.classID equals c.classID
select new {
s.studentID, c.classID, s.firstName, s.middleName,
s.lastName, s.age, c.className});
dgStudents.ItemsSource = data.ToList();
}
现在我希望我的TextBox在DataGrid中填充SelectedItem。我在SelectionChanged事件中有这个代码:
dbStudentEntities context = new dbStudentEntities();
try
{
txtFirst.Text = ((tblStudent)dgStudents.SelectedItem).firstName.ToString();
txtMiddle.Text = ((tblStudent)dgStudents.SelectedItem).middleName.ToString();
txtLast.Text = ((tblStudent)dgStudents.SelectedItem).lastName.ToString();
txtAge.Text = ((tblStudent)dgStudents.SelectedItem).age.ToString();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
但每次我选择一行时,都会弹出此错误:
无法投射类型的对象 '<> f__AnonymousType0
7[System.Int32,System.Int32,System.String,System.String,System.String,System.Nullable
1 [System.Int32],System.String]' 输入'EFStudents.tblStudent'。
我该怎么办?
答案 0 :(得分:0)
在.xaml文件中:
<DataGrid Name="dgStudents" AutoGenerateColumns="True">
</DataGrid>
要创建对象列表,可以尝试:
List<tblStudent> data = context.tblStudents.ToList();
dgStudent.ItemsSource = data;
我可能会犯一些语法错误,所以如果它不起作用,请查看编译器错误。
首先确保de数据位于数据网格中,然后您可以担心选择项目时会发生什么。
答案 1 :(得分:0)
好的,首先,我假设您使用EntityFramework,而您的Student类看起来像是:
public class Student
{
public int Id {get;set;}
public string Name {get;set;} // and other names and age and so on
public ICollection<Class> Classes {get;set;} // classes to which student attends
}
// your context
public class dbStudentEntities : DbContext
{
public DbSet<Student> tblStudents {get;set;} // in CodeFirst this is enough to also create Classes table
}
// then to populate DataGrid:
using(var ctx = new dbStudentEntities()) // this is your context, disposing it is important
{
var students = ctx.Students.Include(x => x.Classes).ToList(); // Student.Classes is not virtual, so we don't have lazy loading, but making it virtual creates ugly proxy. You can read up on that
dataGrid.ItemsSource = students;
}
你不需要那么难看的LINQ - EF可以为你做的工作。
现在DataGrid.SelectedItem将是Student类型,因此您可以使用您的强制转换。