将数据绑定到列表框的ADO.NET实体框架 [英] Databind ADO.NET Entity Framework to ListBox

查看:97
本文介绍了将数据绑定到列表框的ADO.NET实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将ADO EF对象类(Materials)附加到ListBox,并在将新材料添加到数据库时自动更新。

I'm trying to attach a ADO EF object class (Materials) to a ListBox, and have it auto-update when a new material is added to the database.

在我当前的代码中,它将显示控件数据源设置之前数据库中的任何项目,但不会更新。

In my current code below, it will show any items that are in the database before the controls datasource is set, but it will not update.

我知道我'在这里缺少一些基本的东西。非常感谢任何帮助!

I know I'm missing something elementary here. Any help is greatly appreciated!

public partial class Main : KryptonForm
{
    private AGAEntities db = new AGAEntities();
    public Main()
    {
        InitializeComponent();
    }

    private void Main_Load(object sender, EventArgs e)
    {
        matList.DataSource = db.Materials;
        matList.DisplayMember = "Name";
    }

    private void newMat_Click(object sender, EventArgs e)
    {
        AddMaterial form = new AddMaterial();
        form.ShowDialog();
    }
}


推荐答案

因为 db.Materials 在添加项目时不会发出通知。您应该使用 BindingList< T> 作为 DataSource

That's because db.Materials doesn't raise a notification when an item is added to it. You should use a BindingList<T> as the DataSource :

private BindingList<Material> _materials;

private void Main_Load(object sender, EventArgs e)
{
    _materials = new BindingList<Material>(db.Materials);
    matList.DataSource = _materials;
    matList.DisplayMember = "Name";
}

private void newMat_Click(object sender, EventArgs e)
{
    AddMaterial form = new AddMaterial();
    if (form.ShowDialog() == DialogResult.OK)
    {
        _materials.Add(form.NewMaterial);
    }
}

(此代码假定您的 AddMaterial class将新项目添加到数据库,并通过 NewMaterial 属性公开它)

(This code assumes that your AddMaterial class adds the new item to the DB and exposes it through a NewMaterial property)

这篇关于将数据绑定到列表框的ADO.NET实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆