Assume I have the following code:
private List<Employee> displayEmp;
public Form1()
{
InitializeComponent();
displayEmp = new List<Employee>();
}
In my Add Button handler:
private void button1_Click(object sender, EventArgs e)
{
string[] selection = comboEmail.GetItemText(comboEmail.SelectedItem).Split(',');
Employee add = new Employee(Convert.ToInt32(selection[0]), selection[1], selection[2], selection[3]);
if (!(comboEmail.SelectedIndex == 0))
{
if(!(listEmail.Items.Contains(add))){
displayEmp.Add(add);;
listEmail.DataSource = null;
listEmail.DataSource = displayEmp;
}
else
{
MessageBox.Show(add.ToString() + " Already Added.");
}
}
}
My Remove Button Handler:
private void button2_Click(object sender, EventArgs e)
{
int indexRemoval = listEmail.SelectedIndex;
if (indexRemoval != -1)
{
displayEmp.RemoveAt(indexRemoval);
listEmail.DataSource = null;
listEmail.DataSource = displayEmp;
}
}
I have a list of employees in a ComboBox that when selected, I add to a listbox. In the my add/remove button handlers, am I doing it correctly? What is the proper practice when you have a collection binded to a control, and you want to add/remove items?
Yes, you are binding your collection correctly.
I would also do:
Name being whatever property within 'Employee' you want displayed in the listbox, else it will try to convert the object to a string.