开发者

Displaying a default image in gridview

How to display a defualt profile image in gri开发者_如何转开发dview if user didn't provided any image.

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


One approach might be to check each row during RowDataBound event to see image exists or not. If it is empty, you can assign a default image 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
        }
    }
}

Do not forget to add RowDataBound event to your GridView definition.

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

Or If you do not want to use RowDataBound event. At Page_Load you can manually go through each Row of GridView and check ImageUrl one by one.

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


This could also be done in a single line in the aspx itself. By using a ternary operator.

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜