Tuesday, June 26, 2012

Displaying "No Image" Picture when no Image is available in database

Here, You can see that how you can display the “NoImage.jpg” picture when you don’t  have any image available in database.

I am going to provide the code snippet in which you can easily handle when the imageURL is null.

Product.aspx :

<asp:DataList ID="dlProductList" runat="server"
<asp:Image ID="imgProduct" runat="server" 
ImageUrl='<%# Bind("ProductImage") %>' />

Product.aspx .cs:

protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
Protected void dlProductList_ItemDataBound(object sender, DataListItemEventArgs e)
        Image imgProduct = (Image)e.Item.FindControl("imgProduct");  //find the Image
        if (String.IsNullOrEmpty(img.ImageUrl))
            img.ImageUrl = "~/images/ImageNotAvailable.jpg";
Protected void BindData ()
        // Replace your Credential	
        SqlConnection conn = new SqlConnection("server=VIMAL;database=DB;uid=sa;pwd=sa123");
        SqlDataAdapter da = new SqlDataAdapter("select * from test", conn);
        DataTable dt = new DataTable();
       dlProductList.DataSource = dt;

I hope that it solve your problem! You can comment if you facing any issue in above. Happy coding! 

No comments:

Post a Comment