Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement in gridview template filed

Tags:

c#

asp.net

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.

like image 575
turzifer Avatar asked May 17 '11 10:05

turzifer


1 Answers

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>
like image 198
Massimiliano Peluso Avatar answered Oct 03 '22 06:10

Massimiliano Peluso