如何在没有URL的情况下隐藏图像控件?

时间:2010-08-24 06:48:17

标签: c# asp.net

我有Repeater控件有图像控制有时这个图像控件没有数据我想隐藏它没有数据我做了代码但它显示为图像没有数据(不可用)请任何人帮助我。 注意:该数据来自数据库,因此Img Had Id来自数据库,但没有值(NULL)

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


    }



}

2 个答案:

答案 0 :(得分:1)

该属性是否已在某处分配了空字符串?请尝试使用string.IsNullOrEmpty

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

作为旁注,可以缩短(选择最适合您的风格):

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

答案 1 :(得分: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);