How do I make a ListBox refresh its item text?

前端 未结 10 1967
后悔当初
后悔当初 2020-12-03 04:42

I\'m making an example for someone who hasn\'t yet realized that controls like ListBox don\'t have to contain strings; he had been storing formatted strings and

10条回答
  •  [愿得一人]
    2020-12-03 04:49

    BindingList handles updating the bindings by itself.

    using System;
    using System.ComponentModel;
    using System.Windows.Forms;
    
    namespace TestBindingList
    {
        public class Employee
        {
            public string Name { get; set; }
            public int Id { get; set; }
        }
    
        public partial class Form1 : Form
        {
            private BindingList _employees;
    
            private ListBox lstEmployees;
            private TextBox txtId;
            private TextBox txtName;
            private Button btnRemove;
    
            public Form1()
            {
                InitializeComponent();
    
                FlowLayoutPanel layout = new FlowLayoutPanel();
                layout.Dock = DockStyle.Fill;
                Controls.Add(layout);
    
                lstEmployees = new ListBox();
                layout.Controls.Add(lstEmployees);
    
                txtId = new TextBox();
                layout.Controls.Add(txtId);
    
                txtName = new TextBox();
                layout.Controls.Add(txtName);
    
                btnRemove = new Button();
                btnRemove.Click += btnRemove_Click;
                btnRemove.Text = "Remove";
                layout.Controls.Add(btnRemove);
    
                Load+=new EventHandler(Form1_Load);
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                _employees = new BindingList();
                for (int i = 0; i < 10; i++)
                {
                    _employees.Add(new Employee() { Id = i, Name = "Employee " + i.ToString() }); 
                }
    
                lstEmployees.DisplayMember = "Name";
                lstEmployees.DataSource = _employees;
    
                txtId.DataBindings.Add("Text", _employees, "Id");
                txtName.DataBindings.Add("Text", _employees, "Name");
            }
    
            private void btnRemove_Click(object sender, EventArgs e)
            {
                Employee selectedEmployee = (Employee)lstEmployees.SelectedItem;
                if (selectedEmployee != null)
                {
                    _employees.Remove(selectedEmployee);
                }
            }
        }
    }
    

提交回复
热议问题