将 ADO.NET 实体框架数据绑定到列表框

发布于 2024-09-14 15:02:50 字数 618 浏览 16 评论 0原文

我正在尝试将 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();
    }
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甲如呢乙后呢 2024-09-21 15:02:50

这是因为 db.Materials 在添加项目时不会发出通知。您应该使用 BindingList 作为 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 属性)

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文