2012-10-24 33 views
1

我想使用find控制方法找到的設計師形象,使其可見,但我不斷收到一個空查找代碼中的形象背後

這是我的代碼:

foreach (ImageShow image in imageList) 
{ 
    Image Showimage = (Image)FindControl(image.imageName); 
    Showimage.Visible = true; 
} 

任何幫助將不勝感激, 在此先感謝

+1

你可以添加一些更多的代碼嗎?也許你的標記和整個代碼背後? –

+1

是image.imageName圖像控制的Id? – pmtamal

+1

常見問題是FindControl只搜索子控件,而不是他們的子元素 –

回答

5

的FindControl並不整個的控制層次搜索,我相信這是一個問題。

嘗試使用以下方法:

public static T FindControlRecursive<T>(Control holder, string controlID) where T : Control 
{ 
    Control foundControl = null; 
    foreach (Control ctrl in holder.Controls) 
    { 
    if (ctrl.GetType().Equals(typeof(T)) && 
     (string.IsNullOrEmpty(controlID) || (!string.IsNullOrEmpty(controlID) && ctrl.ID.Equals(controlID)))) 
    { 
     foundControl = ctrl; 
    } 
    else if (ctrl.Controls.Count > 0) 
    { 
     foundControl = FindControlRecursive<T>(ctrl, controlID); 
    } 
    if (foundControl != null) 
     break; 
    } 
    return (T)foundControl; 
} 

用法:

Image Showimage = FindControlRecursive<Image>(parent, image.imageName); 

你的情況,家長是這樣的,例如:

Image Showimage = FindControlRecursive<Image>(this, image.imageName); 

你可以使用它沒有ID,然後會發現第一個出現的T:

Image Showimage = FindControlRecursive<Image>(this, string.Empty); 
+0

我得到一個錯誤:錯誤非泛型方法'System.Web.UI.Page.FindControl(字符串)'不能用於類型參數 –

+1

哦對不起,我改名方法名,修復 –

+0

非常感謝你:) –

1
foreach (ImageShow image in imageList) 
{ 
    Image showimage = FindControl(image.imageName) as Image; 
    if(showimage != null) 
    { 
     showimage .Visible = true; 
    } 
} 
+0

謝謝burning_LEGION,但這並沒有工作 –