在表单初始化时调用ShowData()
以在初始化时填充您的列表框
public Department()
{
InitializeComponent();
ShowData();
}
ShowData()
方法、BindingSource
位置DisplayMember
和ValueMember
设置
private void ShowData()
{
using (var uow = new UnitOfWork(new SellContext()))
{
listBox1.DataSource = uow.Departments.GetAll().ToList();
listBox1.DisplayMember = "DepartmentName";
listBox1.ValueMember = "DepartmentId";
//listBox1.Invalidate();
}
}
在下面的实现中,当从数据库中删除部门时,列表框会使用当前集合刷新
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();
}
}