已提交 GridView 模板中的 if 语句

本文关键字:if 语句 提交 GridView | 更新日期: 2023-09-27 17:56:45

我有一个网格视图。 其数据源是从数据库加载的数据表。在此网格视图中,我有一个模板列。此列的内容不是直接从数据库中提取的,而是使用当前项目的 id 来命名并在图像目录中查找该名称。模板字段为:

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

并非所有项目都有图像,所以我想检查这个文件是否存在。如果是这样,我想使用上面的代码来放置它,如果没有,我想将该字段留空。在.cs文件中,这是一个条件设置为 File.Exist() 的 if 语句的问题。但是我在.aspx文件中找不到执行此操作的语法。这是否可能,如果可能,如何?谢谢。

已提交 GridView 模板中的 if 语句

您可以在

RowDataBound 事件上对此行为进行编码。

记住要使图像运行="服务器"

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

我认为您应该选择上述解决方案。

反正只需添加以下内容

<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 标签有一个名为 onerror 的事件。因此,如果您的要求是在找不到图像时执行某些操作,请执行类似操作。

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