Search code examples
c#formscastingpicturebox

How do I solve an "InvalidCastException" in C#?


I am getting a run-time error which tells me that it is unable to cast an object of type PictureBox to type MusicNote (MusicNote inherits from PictureBox.)

private void Note_MouseDown(object sender, MouseEventArgs e)
    {
        //try
        //{
            foreach (MusicNote mn in panel2.Controls) //this is where the error occurs
            {
                if (sender == mn)
                {
                    if (e.Button == MouseButtons.Right)
                    {
                        count = 0;
                        timer1.Start();
                        sp.SoundLocation = MusicNote_path + mn.note + ".wav";
                        sp.Play();
                    }
                if (e.Button == MouseButtons.Left)
                {
                    dragging = true;
                    mn.BackColor = Color.HotPink;


                }

Below is a part of the MusicNote class, including the constructor, to show what happens each time a MusicNote is constructed:

class MusicNote : PictureBox
{
    public int notepitch;
    public int noteduration;
    public String noteshape;
    public String note;
    enum Accid { sharp, flat, sole };

    public static String NoteImage_path = Environment.CurrentDirectory + @"\Notes-Images\\";
    public static int xLoc = 30;
    public int yLoc = 0;

    System.Timers.Timer timer1 = new System.Timers.Timer();

    public MusicNote(int iNotepitch, int iDuration, String iBnoteShape, String iNote)
    {
        notepitch = iNotepitch;
        noteduration = iDuration;
        noteshape = iBnoteShape;
        note = iNote;


        ImageLocation =  NoteImage_path + noteshape + ".bmp";
        BackColor = Color.Transparent;
        ClientSize = new Size(35, 35);
        //BringToFront();


        Location = new Point(xLoc, getyLoc(iNote));
        xLoc += 37;
    }

This is how the panel is being populated:

MusicNote mn = new MusicNote(mk.getMusicNote(), duration, bNoteShape, mk.getNote());
mn.MouseDown += new MouseEventHandler(Note_MouseDown);
mn.MouseUp += new MouseEventHandler(Note_MouseUp);
mn.MouseClick += new MouseEventHandler(Note_MouseClick);

panel2.Controls.Add(mn); //adding MusicNote component to MusicStaff (panel2) collection

Edit: You can view the error here.

Any help is appreciated, thanks.


Solution

  • To loop over MusicNote instances only, you can use the OfType extension method from LINQ:

    foreach (MusicNote mn in panel2.Controls.OfType<MusicNote>()) {
       // do stuff
    }