Home > DeveloperSection > Forums > how to access my form's panel in my class
Mark Devid
Mark Devid

Total Post:102

Points:714
Posted on    December-18-2013 1:08 AM

 C# C# 
Ratings:


 1 Reply(s)
 914  View(s)
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"



ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    December-18-2013 1:34 AM

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


Don't want to miss updates? Please click the below button!

Follow MindStick