简体   繁体   中英

How do i get a list of object in a Listbox?

I was trying to create a personal list using WinForms. I try to create a new entry via button click. I have a list of objects with string properties Name and Number .

How can I show the list of objects in my ListBox?

namespace sometestname
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void Personallistshow(object sender, EventArgs e)
        {

        }

        public void NewItemButton_Click(object sender, EventArgs e)
        {
            Personallist.Add(new Entrys() { Name = NameBox.Text, Number = Numbox.Text });
        }

        public List<Entrys> Personallist= new List<Entrys>();
    }

        public partial class Entrys
        {
            public string Name { get; set; }
            public string Number { get; set; }

        }
}

The user has 2 Textboxfields. If they click the NewItemButton , than create a new Entrys object. This new Entrys object should be added to Personallist object and ListBox should show the updated list.

List<Entrys> someList = ...;
Personallist.DataSource = someList;

You should use a bindinglist and set the datasourcebinding after initializing your form.

Something like:

 public partial class Form1 : Form
{
    public BindingList<Entrys> Personallist = new BindingList<Entrys>();
    public Form1()
    {
        InitializeComponent();
        comboBox1.DataSource = Personallist;
        comboBox1.DisplayMember = "Name";
        comboBox1.ValueMember = "Number";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Personallist.Add(new Entrys() { Name = "TESTNAME", Number = "TESTNR" });
    }
}
public partial class Entrys
{
    public string Name { get; set; }
    public string Number { get; set; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM