繁体   English   中英

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

[英]What is the correct way to use Entity Framework as datasource for DataGridView?

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

在此处输入图片说明

但是现在我的项目 + DataSet 中有实体框架,我怎么能只使用实体框架......我很困惑。

artiklBindingSource是自动生成的,我只想使用 EF 作为数据源,现在我artiklBindingSource了不需要的数据集。

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

  1. 单击添加项目数据源以打开数据源配置向导
  2. 选择数据源类型中选择对象并单击下一步
  3. Select Data Source Objects 中选择要添加到数据源的类,然后单击Finish
  4. 它将向您的表单添加一个BindingSource ,该表单用作DataGridView 的数据源,您应该加载数据并将数据设置为BindingSourc 的DataSource ,然后数据将显示在您的网格中。 例如加载数据。

这是代码示例:

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();
        }
    }
}

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

dataGridViewStudents.DataSource = schoolContext.Students.ToList<Student>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM