首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataGrid SelectedItem to TextBox

DataGrid SelectedItem to TextBox
EN

Stack Overflow用户
提问于 2018-06-06 06:31:52
回答 2查看 329关注 0票数 0

我有这段代码来填充我的DataGrid

代码语言:javascript
复制
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事件中有以下代码:

代码语言:javascript
复制
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__AnonymousType07[System.Int32,System.Int32,System.String,System.String,System.String,System.Nullable1System.Int32,System.String类型的对象强制转换为“EFStudents.tblStudy”。

我该怎么办?

EN

回答 2

Stack Overflow用户

发布于 2018-06-06 06:38:45

在您的.xaml文件中:

代码语言:javascript
复制
<DataGrid Name="dgStudents" AutoGenerateColumns="True">
</DataGrid>

要创建对象列表,可以尝试:

代码语言:javascript
复制
List<tblStudent> data = context.tblStudents.ToList();
dgStudent.ItemsSource = data;

我可能犯了一些语法错误,所以看看编译器错误是什么,如果它不能工作。

首先,确保data在datagrid中,然后您可以担心在选择一个项时会发生什么。

票数 0
EN

Stack Overflow用户

发布于 2018-06-06 09:39:04

好的,首先,我假设您使用的是EntityFramework,而您的学生类看起来很像:

代码语言:javascript
复制
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将是类型的学生,所以你可以使用你的演员。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50713612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档