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