HOW TO ACCESS MY FORM'S PANEL IN MY CLASS

Mark Devid

Total Post:102

Points:714
Posted by  Mark Devid
C# 
C#
 1164  View(s)
Ratings:
Rate this:

I have a form and in the form I have a panel named : mypanel

now I want to write a class and in this class I want to use this:

foreach (Control cont in mypanel.Controls)

        {

            // do sth

        }

but it is impossible, please help me how to access my form's panel in my class

I use this code :

foreach (Control cont in mypanel.Controls)

            {

                if (cont is PictureBox)

                {

                    string path = @"" + Application.StartupPath + "\\Image\\";

                    cont.BackgroundImage = Image.FromFile(path + Rnd.Next(7).ToString() + ".png");

                }

            }

and I have this Error:

"the name 'mypanel' does not Exist in the current context"

  1. ezra heywood

    Post:145

    Points:1019
    Re: how to access my form's panel in my class

    Hi Mark,

    Check if the type of control is Panel and cast it.

    foreach (Control cont in mypanel.Controls)

    {

        if(cont is Panel)

        {

            Panel myPanel = (Panel)cont;

            MessageBox.Show(myPanel.Name);

        }

    }

    You need to cast the control into PictureBox since not all control contains the specific property you want to set,

    PictureBox pBox = (PictureBox)cont;

    pBox.BackgroundImage = Image.FromFile(path + Rnd.Next(7).ToString() + ".png");

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!