【发布时间】:2018-06-06 06:31:52
【问题描述】:
我有这个代码来填充我的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.Nullable1[System.Int32],System.String]' 输入“EFStudents.tblStudent”。
我该怎么办?
【问题讨论】:
-
您没有将 tblStudent 对象添加到列表中。我不确定您是否可以在 winforms 中执行此操作,但在 wpf 中您只需将 tblStudent 对象列表作为 ItemsSource 添加到 listView。 new { } 是一个匿名类,所以这个错误是有道理的
-
我使用 WPF 而我没有使用 listview。
-
那么就完全没有问题了。只要看看我的回答,如果你的 DataGrid 上有 AutoGenerateColumns="True" ,你应该很高兴
-
很抱歉问这位先生,但是如何?我是 wpf 的新手。
-
我认为错误在这里:
((**tblStudent**)dgStudents.SelectedItem).firstName.ToString();。因为我加入了 linq 查询来填充我的 DataGrid,但我只从 tblStudent 获取 SelectedItem。我不知道用什么来代替它。
标签: c# wpf entity-framework