Databinding ArrayList for ListBox in VB.NET?

I work in VB.NET

I have an ArrayList named Invoices populated with objects of the Invoice class.

I want the data to associate this with a ListBox, as the contents of the ArrayList are updated and modifies the updates of the ListBox. I implemented the .ToString function in the Invoice class, I just don't know how I would associate an ArrayList with a ListBox.

Any suggestions?

+3
source share
1 answer

I will assume that these are winforms.

If you want two-way data binding, you need a few things:

  • / .., , IBindingList; , BindingList<T> - (ArrayList ...)
  • , INotifyPropertyChanged ( "* ", BindingList<T>)

, ListBox . ; #, ...

using System;
using System.ComponentModel;
using System.Windows.Forms;
class Data : INotifyPropertyChanged{
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this,
            new PropertyChangedEventArgs(propertyName));
    }
}
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Button btn1, btn2;
        BindingList<Data> list = new BindingList<Data> {
            new Data { Name = "Fred"},
            new Data { Name = "Barney"},
        };
        using (Form frm = new Form
        {
            Controls =
            {
                new ListBox { DataSource = list, DisplayMember = "Name",
                     Dock = DockStyle.Fill},
                (btn1 = new Button { Text = "add", Dock = DockStyle.Bottom}),
                (btn2 = new Button { Text = "edit", Dock = DockStyle.Bottom}),
            }
        })
        {
            btn1.Click += delegate { list.Add(new Data { Name = "Betty" }); };
            btn2.Click += delegate { list[0].Name = "Wilma"; };
            Application.Run(frm);
        }
    }
}
+2

Source: https://habr.com/ru/post/1715170/


All Articles