简体   繁体   English

在运行时PictureBox控件C中找不到图像属性

[英]Image property not found in runtime PictureBox control c#

Image property not found from the item variable. 从item变量中找不到图像属性。 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 . 您的item变量仍然是Control类型。 Checking that the instance it is referencing is a PictureBox does not change that. 检查它所引用的实例是否为PictureBox不会改变它。 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: 使用as运算符,如下所示:

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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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