我是在VS2013与SQL Server2014中创建的数据库链接的工作。我正在编写简单的函数,比如添加、创建、删除和更新记录。所有函数都运行正常,但我希望我的所有记录都应该显示在WPF中的GridView中。
我找了很久,但没有找到任何答案。我写了下面的代码来添加记录:
DataContext dc = new DataContext();
MyNew_DBEntities db = new MyNew_DBEntities();
Student st = new Student();
st.First_Name = First_Name.Text;
st.Last_Name = Last_Name.Text;
st.Department = Department.Text;
db.Students.Add(st);
db.SaveChanges();
MessageBox.Show("Record Added Seccessfuly", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
我希望在添加之后,我输入的所有记录都应该显示在GridView中,依此类推。删除和更新记录的相似性也是如此。
发布于 2015-12-06 05:37:57
你会想要使用你的DbContext并得到你想要在网格上显示的对象图。
MyNew_DBEntities db = new MyNew_DBEntities();
var StudentCollection = db.Students.ToList();
您可以执行如上所示的ToList()并发送到数据网格的ItemSource。
然后在DataGrid上设置数据绑定
<DataGrid ItemsSource="{Binding StudentCollection}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="FirstName">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding First_Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
但是,我会将ItemSource数据绑定设置为ObservableCollection。如果集合发生变化,ObservableCollection会自动更新UI,唯一的问题是你不能很容易地转换成ObservableCollection。您需要编写一个扩展方法来完成这项工作。我通常使用以下几种方法
public static class CollectionUtility
{
public static ObservableCollection<T> ToObservableCollection<T>(
this IEnumerable<T> enumeration)
{
return new ObservableCollection<T>(enumeration);
}
}
如果现在实现此扩展方法,则可以使用此方法代替.ToList()
var StudentCollection = db.Students.ToObservableCollection();
https://stackoverflow.com/questions/34110849
复制相似问题