2010-08-24 88 views
2

我有有圖像控制有時這個圖像控制hadnot數據,我想隱藏它,當它沒有數據時,我做了代碼,但它顯示爲圖像沒有數據(不可用),請任何人幫我的Repeater控制。 注:數據來自數據的基礎上使圖只好標識從數據庫中,但沒有值(NULL)如何在沒有URL的情況下隱藏圖像控件?

protected void DLHome_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 

    Image Img = e.Item.FindControl("ModelLogo") as Image; 
    using (SqlConnection con = Connection.GetConnection()) 
    { 
     string Sql = "Select Logo From Model"; 
     SqlCommand com = new SqlCommand(Sql, con); 
     com.CommandType = CommandType.Text; 
     SqlDataReader dr = com.ExecuteReader(); 
     if (dr.Read()) 
     { 
      string Img2 = dr["Logo"].ToString(); 
      if (Img2 == System.DBNull.Value.ToString()) 
      { 
       Img.Visible = false; 
      } 
     } 


    } 



} 

回答

1

一個更好的方式來做到這將是檢索原始查詢中的徽標數據用於填充您的中繼器。然後,您將能夠基於該數據在圖像上設置Visible屬性,而不必在每行綁定時執行新的數據庫查詢。這會提高你的頁面的性能。

關於你已經發布的代碼,你不及格的圖片ID給SqlCommand

string Sql = "Select Logo From Model where ImageId = @ImageId"; 

    //Assuming List<ImageModel> is what you are binding to the repeater 
    ImageModel model = e.Item.DataItem as ImageModel; 
    com.Parameters.Add("@ImageId", SqlDbType.Int32, model.ImageId); 
1

難道是財產已經分配了某處一個空字符串?嘗試使用string.IsNullOrEmpty代替:

if (string.IsNullOrEmpty(Img.ImageUrl)) 
{ 
    Img.Visible = false; 
} 

作爲一個側面說明,這可以縮短(選擇何種風格最適合你):

Img.Visible = !string.IsNullOrEmpty(Img.ImageUrl); 
+0

注:數據來自數據的基礎上使圖只好標識從數據庫中,但沒有值(NULL) – Myworld 2010-08-24 07:03:16

相關問題