How to refresh DataSource of a ListBox

后端 未结 7 1235
轮回少年
轮回少年 2020-11-27 04:39

Form has one Combobox and one ListBox. When the \"Add\" button is clicked, I want to add the selected item from the ComboBox to the ListBox.

public partial c         


        
7条回答
  •  独厮守ぢ
    2020-11-27 05:12

    Call ShowData() when the form initializes to populate your listbox on initialization

     public Department()
            {
                InitializeComponent();
                ShowData();
            }
    

    ShowData() Method, where BindingSource, DisplayMember and ValueMember are set

    private void ShowData()
                {
                    using (var uow = new UnitOfWork(new SellContext()))
                    {
                        listBox1.DataSource = uow.Departments.GetAll().ToList();
                        listBox1.DisplayMember = "DepartmentName";
                        listBox1.ValueMember = "DepartmentId"; 
                        //listBox1.Invalidate();       
                    }
                }
    

    In the implementation below when a department is deleted from database the listbox refreshes with the current collection

    private void button1_Click(object sender, EventArgs e)
        {
            try {
                using (var uow = new UnitOfWork(new SellContext()))
                {
                    int count = uow.Departments.FindDepartmentByName(txtDeptName.Text.ToString());
                    if (count>0)
                    {
                        MessageBox.Show("This Department Already Exists", "SellRight", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
    
                    else
                    {
                        department dept = new department();
                        dept.DepartmentName = txtDeptName.Text.ToString();
                        uow.Departments.Create(dept);
                        if (uow.Complete() > 0)
                        {           
                            MessageBox.Show("New Department Created", "SellRight", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            txtDeptName.Text = "";
                            ShowData();      
                        }
                        else
                        {
                            MessageBox.Show("Unable to add Department", "SellRight", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtDeptName.Text = "";
                            ShowData();
                        }
                    }
                }                              
            }
            catch(Exception ex)
            {
                ex.ToString();
            }
        }
    

提交回复
热议问题