2015-04-26 56 views
2

未找到項目變量的圖像屬性。我的代碼是 -在運行時PictureBox控件c中找不到圖像屬性#

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

請幫忙嗎?

+0

如果任何答案充分解決了您的問題,您可能希望選擇它作爲答案,因此可以從「未答覆」列表中刪除該問題。 – Alex

+0

@Alex - 好吧,我要標記它。謝謝。 –

回答

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

它的工作原理。謝謝。 –

+1

不客氣。解釋爲什麼這種方法有效,而且你所做的事情沒有奏效,清楚嗎? – Alex

+0

我希望現在很清楚。 +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; 
     } 
    } 
} 
相關問題