运行时没有找到图像属性PictureBox控件c#

时间:2015-04-26 05:21:55

标签: c# winforms

未在item变量中找到图像属性。我的代码是 -

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

请帮忙吗?

2 个答案:

答案 0 :(得分:2)

您的item变量仍然属于Control类型。检查它引用的实例是PictureBox不会改变它。您可以将代码更改为:

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

答案 1 :(得分:1)

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