在gridview中显示默认图像

时间:2011-08-23 13:16:42

标签: asp.net image gridview

如果用户未提供任何图像,如何在gridview中显示默认配置文件图像。

if (fileUpload.PostedFile == null) 
{ 
    lblStatus.Text = "No file specified."; 
    return; 
} 
else
{        
{

2 个答案:

答案 0 :(得分:2)

一种方法可能是在RowDataBound事件期间检查每一行以查看图像是否存在。如果为空,则可以指定默认图像URL。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{        
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        Image image= (Image)e.Row.FindControl("ImageForPerson");

        if (image != null && image.ImageIrl == "")
        {
            image.ImageUrl = // default image url goes here
        }
    }
}

不要忘记将RowDataBound事件添加到GridView定义中。

<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" />

或者如果您不想使用RowDataBound事件。在Page_Load中,您可以手动浏览GridView的每一行并逐个检查ImageUrl。

protected void Page_Load(object sender, EventArgs e)
{
     foreach(GridViewRow gvr in GridView1.Rows)
     {
         Image image = (Image)gvr.FindControl("ImageForPerson");

         if (image != null && image.ImageIrl == "")
         {
             image.ImageUrl = // default image url goes here
         }
     }
}

答案 1 :(得分:0)

这也可以在aspx本身的一行中完成。通过使用三元运算符。

<asp:Image ID="Image1" runat="server" ImageUrl='<%# !string.IsNullOrEmpty(Eval("userImage").ToString()) ? "/images/" + Eval("userImage") : "/images/noimage.jpg" %>' />
相关问题