簡體   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