开发者

if statement in gridview template filed

I have a gridview. its data source is a datatable that is loaded from the database. In this gridview, i have a template column. The content of this column is not directly pulled from the database but instead, i use the id of the current item to make a name and look for that name in a开发者_开发百科 directory of images. The template field is:

<asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>' />
    </itemtemplate>
</asp:TemplateField>

Not all the items have images so I would like to check if this file exists. If it does, I'd like to use the above code to place it, if it doesn't i'd like to leave the field empty. In the .cs file this is a matter of an if statement with the condition set to File.Exist(). But I could not find the syntax to do it in the .aspx file. Is this possible and if so how? Thanks.


you could code this behavior on the RowDataBound event. somethink like the below

Remember to make the image runat="server"

 protected void GridViewProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if(e.Row.RowType = DataControlRowType.DataRow){
    if(!File.Exist(yourFileName){
        //hide the image
        var img=e.Row.FindControl("theImageId");
        img.visible=false;
     }
   }
}

I think you should go for the above solution.

anyway Just add the below

<asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>' 
    <%= File.Exists("yourFileName")? string.Empty : "style='display: none'" %> />
    </itemtemplate>
</asp:TemplateField>


img tag has an event called onerror. So, if your requirement is to do something if the image is not found, do something like this.

onerror="this.src='Images/default.png'"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜