将Entity Framework用作DataGridView的数据源的正确方法是什么?

时间:2017-02-08 13:39:54

标签: c# winforms entity-framework datagridview datasource

我尝试通过DataGridView Designer设置DataSource但是没有在那里列出,然后我通过生成DataSet的向导生成了新的数据源。

enter image description here

但是现在我的项目+ DataSet中有Entity Framework我怎么才能使用Entity Framework ...我很困惑请帮忙

artiklBindingSource是自动生成的我只想使用EF作为数据源,现在我遇到了不需要的DataSet和一大堆乱七八糟。

2 个答案:

答案 0 :(得分:12)

要添加要与 DataGridView任务面板中的DataGridView一起使用的数据源,请打开选择数据源:组合框,然后:

  1. 点击添加项目数据源以打开数据源配置向导
  2. 选择数据源类型选择对象,然后单击下一步
  3. 选择数据源对象中选择要添加到数据源的类,然后单击完成
  4. 它会将 BindingSource 添加到表单中,该表单用作 DataGridView DataSource ,你应该加载数据并将数据设置到 BindingSourc DataSource ,然后数据将显示在您的网格中。例如,加载数据。
  5. 以下是代码示例:

    using System;
    using System.Windows.Forms;
    using System.Data.Entity;
    namespace WindowsFormsApplication
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            SampleDBEntities db;
            private void Form1_Load(object sender, EventArgs e)
            {
                db = new SampleDBEntities();
                db.Products.Load();
                this.productBindingSource.DataSource = db.Products.Local.ToBindingList();
            }
            private void SaveButton_Click(object sender, EventArgs e)
            {
                db.SaveChanges();
            }
            private void Form1_FormClosed(object sender, FormClosedEventArgs e)
            {
                db.Dispose();
            }
        }
    }
    

答案 1 :(得分:1)

不知道这是否是最快的方法,但是更简单:

dataGridViewStudents.DataSource = schoolContext.Students.ToList<Student>();
相关问题