Click here to Skip to main content
16,020,114 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Why I am getting an error when i click on the command box?, i want to get the salary of that particular employee

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.ListBox lstCustomers;
        public Form1()
        {
            InitializeComponent();
            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 lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
        {
            Customer cust = (Customer)lstCustomers.SelectedItem;
            MessageBox.Show("Birth Date: " + cust.BirthDate.ToShortDateString());
        }

        private void InitializeComponent()
        {
            this.lstCustomers = new System.Windows.Forms.ListBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // lstCustomers
            // 
            this.lstCustomers.FormattingEnabled = true;
            this.lstCustomers.Location = new System.Drawing.Point(12, 12);
            this.lstCustomers.Name = "lstCustomers";
            this.lstCustomers.Size = new System.Drawing.Size(120, 95);
            this.lstCustomers.TabIndex = 0;
            this.lstCustomers.SelectedIndexChanged += new System.EventHandler(this.lstCustomers_SelectedIndexChanged);
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(170, 31);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(308, 230);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.lstCustomers);
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }


        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (Employee emp in lstCustomers.Items)
            {
                //Employee emp = (Customer)lstCustomers.Items;
                MessageBox.Show(Convert.ToString(emp.Salary),"Salary");

            }

        }

    }
    public class Customer
    {
        public string FirstName;
        public string LastName;
        public DateTime BirthDate;

        public Customer() { }

        public Customer(string firstName, string lastName, DateTime birthDate)
        {
            FirstName = firstName;
            LastName = lastName;
            BirthDate = birthDate;
        }

        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
    }

    public class Employee : Customer
    {
        //public string FirstName;
        //public string LastName;
        //public DateTime BirthDate;
        public double Salary;

        public Employee() { }



        public Employee(string firstName, string lastName, DateTime birthDate, double salary)
            :base(firstName,lastName,birthDate)

        {
            Salary = salary;
            //FirstName = firstName;
            //LastName = lastName;
            //BirthDate = birthDate;
        }

        public override string ToString()
        {
            return base.ToString() + " " + Salary ;
        }
    }



}
Posted
Updated 10-Dec-10 22:21pm
v2
Comments
Abdul Quader Mamun 11-Dec-10 4:22am    
Use pre tag for better reading.
Sandeep Mewara 11-Dec-10 4:22am    
What is command box?
datt265 11-Dec-10 4:32am    
When I click on the command box, I want to show as a message box, the objects in class Employees (I just want to show the salary)
datt265 11-Dec-10 4:33am    
private void button1_Click(object sender, EventArgs e)
{
foreach (Employee emp in lstCustomers.Items)
{
//Employee emp = (Customer)lstCustomers.Items;
MessageBox.Show(Convert.ToString(emp.Salary),"Salary");

}

}
Toli Cuturicu 11-Dec-10 7:51am    
You have already been politely asked what a "command box" was.
Instead of answering the question, you reitereted the same phrase.

1 solution

MIDL
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));

C#
private void button1_Click(object sender, EventArgs e)
{
    foreach (Employee emp in lstCustomers.Items)
    {
        //Employee emp = (Customer)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:
C#
foreach (Customer cust in list.Items)
    {
    Employee emp = cust as Employee;
    if (emp != null)
        {
        Console.WriteLine(emp.name);
        }
    }
 
Share this answer
 
Comments
datt265 11-Dec-10 5:13am    
Thanks this is what I was looking for

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900