Click here to Skip to main content
15,883,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Friends,
I need your help please.

I have a gridview that displays student records with pictures very well, but I want to display a dummy picture(say noimage.png) in the row where there is no image(NULL or Empty) in the database. I store the image path and image name in table and store the Images in a folder.
How can I do this?
Kindly help,
Thanks
Ravi.

What I have tried:

This is my .aspx page
ASPX
<asp:GridView ID="GridView1" runat="server" cellpadding="5" AutoGenerateColumns = "false" GridLines="Horizontal" AllowPaging ="true" PageSize = "8" Width="100%">
<Columns>
    <asp:BoundField DataField = "SID" HeaderText = "Student ID" ItemStyle-Width="5%"/>
    <asp:BoundField DataField = "SName" HeaderText = "Name" HtmlEncode = "false" ItemStyle-Width="30"/>
    <asp:ImageField DataImageUrlField="Image" HeaderText="Student Picture"/>
</Columns>
</asp:GridView>

and here is my .cs Page
C#
if (!IsPostBack)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
    string query = "select SID, SName, Image from Students";
    SqlDataAdapter sda = new SqlDataAdapter(query, con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();
}
Posted
Updated 9-Sep-21 3:17am
v2

Change your query:
C#
const string query = "select SID, SName, IsNull(NullIf(Image, ''), @DefaultImage) Image from Students";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
sda.SelectCommand.Parameters.AddWithValue("@DefaultImage", "~/images/no-picture.jpg");
Specify the path of your default picture as the value of the @DefaultImage parameter.
 
Share this answer
 
Comments
ravitv 9-Sep-21 8:38am    
Sorry Richard, I dont understand,
My dummy image is in "~img/noimage.png" folder.
How can I use this?
Will sda.SelectCommand.Parameters.AddWithValue("@DefaultImage", "~img/noimage.png");
work with
...
.....
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();

Sorry for troubling you.
Richard Deeming 9-Sep-21 8:39am    
Yes - whatever path you pass to the AddWithValue method will be returned for any images which are null or empty.
Sorry again, Richard - I had to resort to old style solution by using

NullDisplayText property

<asp:ImageField DataImageUrlField="Image" HeaderText="Profile Picture" ControlStyle-Width="25" ItemStyle-Width="25" ControlStyle-Height="25" ItemStyle-Height="25" NullDisplayText='<img src="img/noimage.png" runat="server" Width="25" Height="25">'/>

I liked a c# solution.
If possible please provide simple sample source code.
But thanks for spending your valuable time.
Ravi
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900