简体   繁体   中英

Image property not found in runtime PictureBox control c#

Image property not found from the item variable. My code is -

foreach (Control item in this.Controls) //Iterating all controls on form
{
    if (item is PictureBox)
    {
        if (item.Tag.ToString() == ipAddress + "OnOff")
        {
            MethodInvoker action = delegate
            { item.Image= }; //.Image property not shown
            item.BeginInvoke(action);
            break;
        }
    }
}

Any help please?

Your item variable still is of the type Control . Checking that the instance it is referencing is a PictureBox does not change that. You could change your code to:

foreach (Control item in this.Controls) //Iterating all controls on form
{
    var pb = item as PictureBox; // now you can access it a PictureBox, if it is one
    if (pb != null)
    {
        if (item.Tag.ToString() == ipAddress + "OnOff")
        {
            MethodInvoker action = delegate
            { 
                pb.Image =  ... // works now
            }; 
            bp.BeginInvoke(action);
            break;
        }
    }
}

Use the as operator, like so:

foreach (Control item in this.Controls)
{
    PictureBox pictureBox = item as PictureBox;

    if (pictureBox != null)
    {
        if (item.Tag.ToString() == ipAddress + "OnOff")
        {
            MethodInvoker action = delegate
            { item.Image= ... };
            item.BeginInvoke(action);
            break;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM