我尝试通过 DataGridView Designer 设置 DataSource,但它没有在此处列出,然后我通过生成 DataSet 的向导生成了新的数据源。
但是现在我的项目中有 Entity Framework + DataSet,我怎么能只使用 Entity Framework...我很困惑。
artiklBindingSource
是自动生成的我只想使用 EF 作为数据源,现在我被不需要的 DataSet 困住了。
最佳答案
添加数据源以与您的 DataGridView
一起使用在 DataGridView Tasks 面板中,打开 Choose Data Source: 组合框,然后:
- 单击添加项目数据源以打开数据源配置向导。
- 在选择数据源类型中选择对象并单击下一步。
- 在Select Data Source Objects中选择您要添加到数据源的类,然后单击Finish。
- 它将添加一个 BindingSource 到您的 Form 中,用作 DataGridView 的 DataSource 并且您应该加载数据并将数据设置到 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();
}
}
}
关于c# - 使用 Entity Framework 作为 DataGridView 的数据源的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42114690/