c# asp.net displaying image in gridview

Yakirbu

I wish to display an image in a gridview.

I have a database with 4 columns - id, author, comment, filename (which holds the img path)

http://postimg.org/image/4loz8t9fb/

I have an image upload method so when the user writes his comment, chooses a photo and clicks submit- his name, the comment and the photo path goes to the database (and the photo itself is uploaded to 'Images' folder in the project folder).

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False"
                   Font-Names = "Arial" Height="375px" Width="498px" DataSourceID="SqlDataSource2" >
                <Columns>

                    <asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" />
                    <asp:BoundField DataField="Comment" HeaderText="Comment" SortExpression="Comment" />
                    <asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" />
                    <asp:TemplateField HeaderText="Image">

                      <ItemTemplate >

                        <asp:Image ID="Image1" runat="server" ImageUrl ='<%# Eval("FileName") %>' height="120px" Width="150px" />

                      </ItemTemplate>

                    </asp:TemplateField>
                </Columns>
                </asp:GridView>

here is the c# code-

protected void addcomment_Click(object sender, EventArgs e)
    {
        string FileName = "";
        if (fileupload.PostedFile != null)
        {
             FileName = Path.GetFileName(fileupload.PostedFile.FileName);
             //Save files to disk
             fileupload.SaveAs(Server.MapPath("Images/" + FileName));

        }




        if (TextBox1.Text.Length > 0)
        {
            string name = firstName + " " + lastName;
            SqlCommand cmd = new SqlCommand("insert into comments values(@name,@comment,@filename)", conn);
            cmd.Parameters.AddWithValue("@name", name);
            cmd.Parameters.AddWithValue("@comment", TextBox1.Text);
            cmd.Parameters.AddWithValue("@filename", Server.MapPath("Images/" + FileName));
            conn.Open();
            cmd.ExecuteNonQuery();
            GridView1.DataBind();
            conn.Close();
            TextBox1.Text = "";
            Response.Redirect(Request.Url.AbsoluteUri);
        }
        else
        {
            TextBox1.Text = "You have to type something buddy!";
        }

    }

The gridview datasource is the sql of course.

Here is an image of the database and the website

http://postimg.org/image/4loz8t9fb/

Anoop B.K

Dont set full path ,

 string savepath = "~/Images/" + Filename;
cmd.Parameters.AddWithValue("@filename", savepath));

just change this line it will work

and even change

 fileupload.SaveAs(Server.MapPath("~/Images/" + FileName));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related