【问题标题】:Databind ADO.NET Entity Framework to ListBox将 ADO.NET 实体框架数据绑定到 ListBox
【发布时间】:2023-03-25 02:49:01
【问题描述】:

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

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

我知道我在这里遗漏了一些基本的东西。非常感谢任何帮助!

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

【问题讨论】:

    标签: c# data-binding ado.net-entity-data-model


    【解决方案1】:

    这是因为db.Materials 在添加项目时不会发出通知。您应该使用 BindingList<T> 作为 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 类将新项目添加到数据库并通过NewMaterial 属性公开它)

    【讨论】:

    • 我喜欢你的解决方案,但是有没有更简单的方法?添加项目时,实体框架不应该引发事件吗?
    • 嗯,db.Materials 不完全是一个集合,它是一个查询。您不会向其中“添加”项目:您将它们添加到数据库中,并且下次执行查询时,将返回新项目。所以在这种情况下发出通知是没有意义的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    相关资源
    最近更新 更多