lstCustomers.Items.Add(new Customer("A", "B", DateTime.Now.AddDays(-10)));
lstCustomers.Items.Add(new Customer("C", "D", DateTime.Now.AddDays(-100)));
lstCustomers.Items.Add(new Customer("F", "G", DateTime.Now.AddDays(-500)));
lstCustomers.Items.Add(new Employee("Z", "Y", DateTime.Now.AddDays(-700), 100.00));
private void button1_Click(object sender, EventArgs e)
{
foreach (Employee emp in lstCustomers.Items)
{
MessageBox.Show(Convert.ToString(emp.Salary),"Salary");
}
}
So: You add both Customer and Employee items to your ListBox. That's fine.
The problem is when you try to access them, you get an exception:
System.InvalidCastException occurred
Message="Unable to cast object of type 'Customer' to type 'Employee'."
Just because you can write code, doesn't mean the compiler will be able to do it!
When you do a
foreach
the code iterates through the list and assigns each one to the variable in turn. If they are not the same type (and Employee and Customer are not the same) tthen it attempts to cast. And it can't do it. You can't cast from a base class to a derived class. So, it complains.
Instead, iterate through the base class, and check what type you have:
foreach (Customer cust in list.Items)
{
Employee emp = cust as Employee;
if (emp != null)
{
Console.WriteLine(emp.name);
}
}