我有这段代码来填充我的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充满SelectedItem in DataGrid。在我的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.Nullable1System.Int32,System.String类型的对象强制转换为“EFStudents.tblStudy”。
我该怎么办?
发布于 2018-06-06 06:38:45
在您的.xaml文件中:
<DataGrid Name="dgStudents" AutoGenerateColumns="True">
</DataGrid>要创建对象列表,可以尝试:
List<tblStudent> data = context.tblStudents.ToList();
dgStudent.ItemsSource = data;我可能犯了一些语法错误,所以看看编译器错误是什么,如果它不能工作。
首先,确保data在datagrid中,然后您可以担心在选择一个项时会发生什么。
发布于 2018-06-06 09:39:04
好的,首先,我假设您使用的是EntityFramework,而您的学生类看起来很像:
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能帮你做这件事。
现在DataGrid.SelectedItem将是类型的学生,所以你可以使用你的演员。
https://stackoverflow.com/questions/50713612
复制相似问题