Save Image Path into Database, Retrieve Image Path by Particular Image ID and Display Image through Gridview

Hi All,

Currently, I have a file upload control in my aspx page to allow user to upload images.

When the user clicks the SAVE button, the image will be saved in a particular folder named 'PMap' that located within the website.

What I am trying to do here is to direct all uploaded images into a common image folder (in this case 'PMap') and then, retrieve the images and displayed it through a Gridview according to its respective image id. I have managed to store all uploaded images into a common image folder, PMap.

However, I hope advice can be given on my following problems...

My problems are:

1) How do I save the physical path of the image in that particular folder into the database under a column named ImgPath, so that I can 'call' and retrieve the image from the folder using ImgPath?

2) How do I ensure that when I retrieve the image from the folder, it's the image of that particular Image ID?

This is my current VB codings:

1    Protected Sub SaveBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
2            Try
4                    ' PMapFU is the name of my file upload control
5                If PMapFU.HasFile = False Then
6                    ' No file uploaded!
7                    ImgStatus.Text = "Please first select an image to upload"
8                Else
9                    ' Display the uploaded file's details
10                   ImgStatus.Text = String.Format( _
11                           "Uploaded file: {0}<br />", _
12                           PMapFU.FileName)
14                   ' Save the file
15                   Dim filePath As String = Server.MapPath("~/PMap/" & PMapFU.FileName)
16                   PMapFU.SaveAs(filePath)
17                   SqlDataSource1.Insert()
18               End If
20               SaveMsg.Text = PNameTxt.Text + " is saved!"
21           Catch ex As Exception
22               SaveMsg.Text = ex.Message.ToString
23           End Try
25       End Sub

I would appreciate it if codings could be given to help me (=

Thanks for all the help in advance!!!

Warm Regards,
12/19/2007 3:30:47 AM 72751 articles. 3 followers. Follow

9 Replies

Similar Articles

[PageSpeed] 56

With regards in saving image path to a temp folder

With regards in displaying images to gridview 


"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
12/19/2007 4:38:32 AM


           You just save the file name in database so that you can retrieve the imagefilename and bind it to any data display controls like datalist or grid view.

you can save filename in database with relation to userid i.e have 2 columns in database

ImageName nvarchar(20),

user id int not null..

 when ur saving the file in Image folder Pmap ,use this format







and save the lbluploadresume.text in database so that you with the uploaded filename userid will be attached so that if u have same filename for different users the new file will replace the old one.

when Your are retreiving the Image  use this code

<Img src='Foldername/<%#DataBinder.Eval(Container.DataItem,"ImageName")%>'


Happy Programming

12/19/2007 4:41:10 AM

hmmm, i don't noe how lehz...

but please juz mark me as answers can liao =)

Computers will take the place of books.Becoz you doesn't have to reach a high shelf anymore! =)
~ Jabalang Lahz

Thanks for building the Internet as a Library.
Thanks for sharing and being helpful.
12/19/2007 6:55:26 AM

u can make use of datalist

<asp:DataList ID="dtlMemberDetails" CssClass="style7" runat="server" BackColor="#b3af99"

BorderColor="White" BorderStyle="None" BorderWidth="2px" CellPadding="6" CellSpacing="6" Width="100%">









<TABLE cellpadding="10" cellspacing="0">


<TR valign="top">

<TD style="WIDTH: 120px,height=150" rowSpan=2 valign="Top" align="left"><%# Comment.ShowImage(Eval("MemberName").ToString().Trim()+".jpg","80","100")%></TD>





<FooterStyle BackColor="#B3AF99" ForeColor="Black" />

<SelectedItemStyle BackColor="#B3AF99" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#B3AF99" Font-Bold="True" ForeColor="#E7E7FF" />

<ItemStyle BackColor="#BFBBA8" ForeColor="Black" BorderColor="White" />






public static string ShowImage(string file, string width, string height)


string strReturn = "";

string filePath;

if (System.IO.File.Exists(HttpContext.Current.Request.PhysicalApplicationPath + "MemberPics\\" + file))


filePath = CommonClass.GetSiteRoot() + "/MemberPics/" + file ;



{ filePath = CommonClass.GetSiteRoot() + "/MemberPics/" + "photo.jpg"; }

strReturn = "<img src='" + filePath + "' border='0' width='" + width + "' height=" + height + ">";

return strReturn;




public static string GetSiteRoot()


string port = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT"];

if (port == null || port == "80" || port == "443")

port = "";


port = ":" + port;

string protocol = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];

if (protocol == null || protocol == "0")

protocol = "http://";


protocol = "https://";

string strOut = protocol + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + System.Web.HttpContext.Current.Request.ApplicationPath;

return strOut;


12/19/2007 7:05:15 AM

Hey All!

Thanks for all the help rendered (=

I would esp like to thank vinz for his second link and shashikantht for his post which proved rather helpful to me (=

However, after several attempts, I still could not get the problem solved! So I would appreciate it if more help can be offered!!!

I did some research myself and came across the following article (please take a look at it if you have the time):

Please look at the topic 'A practical example of file and directory manipulation in ASP.NET' in the article.

It is what I have been wanting to do, but I just couldn't get the desired results after several attempts.

Is there any way I can make use of the codings in the article and incoporate them into my existing codes to make things work?

I just want to insert the image path into my sql database so that it can be retrieved later according to its respective imgID!!!


Thanks for all the effort in advance!!!




12/20/2007 11:50:40 AM

Up you go!

Thanks for building the Internet as a Library.
Thanks for sharing and being helpful.
12/21/2007 4:45:33 AM

say somemore...

Thanks for building the Internet as a Library.
Thanks for sharing and being helpful.
12/23/2007 3:07:19 PM

Hi All!

Thanks for all your help!!!

I have managed to solve the error on my own (=

So here is my FINAL solution for inserting image path and other data into the database... Once this is done, displaying wasn't a problem after that.

My VB codes are as follows:

1    Protected Sub SaveBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
2            Try
4                Dim
filename As String = ""
5                Dim filecontent As String = ""
6                Dim path As String = Server.MapPath("~/PMap/Main/" & PMapFU.FileName)

7                Dim allowExtension As String() = {".gif", ".png", ".jpeg", ".jpg", ".bmp"}
10               If PMapFU.HasFile = False Then
11                   ' No file uploaded!
12                   ImgStatus.Text = "Please first select an image to upload"
14               Else
15                   Dim
fileExtension As String = System.IO.Path.GetExtension(PMapFU.FileName).ToLower
16                   Dim i As Integer
18                   'Check file type
19                   For i = 0 To allowExtension.Length - 1
20                       If fileExtension = allowExtension(i) Then
22                           ' Save the file in folder
23                           PMapFU.PostedFile.SaveAs(path)
25                           ' Display the uploaded file's details
26                           ImgStatus.Text = String.Format( _
27                                  "Uploaded file: {0}<br />", _
28                                   PMapFU.FileName)
29                       End If
30                   Next
31               End If
33               Dim
cnn As Data.SqlClient.SqlConnection
34               Dim cmd As Data.SqlClient.SqlCommand
35               Dim param As Data.SqlClient.SqlParameter
36               Dim strSQL As String
38               strSQL = "Insert Into MainProcess( ProcessName, ProcessPGU, EntityBelongTo, TeamBelongTo, ProcessOwner, CurrentVersion, VersionDate, FirstIssueDate, PreparedBy, ApprovedBy, Purpose, Description, ProcessMap) Values( @ProcessName, @ProcessPGU, @EntityBelongTo, @TeamBelongTo, @ProcessOwner, @CurrentVersion, @VersionDate, @FirstIssueDate, @PreparedBy, @ApprovedBy, @Purpose, @Description, @ProcessMap)"
40               Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=""|DataDirectory|\Processes.mdf"";Integrated Security=True;User Instance=True"
41               cnn = New Data.SqlClient.SqlConnection(connString)
43               cmd = New Data.SqlClient.SqlCommand(strSQL, cnn)
45               param = New Data.SqlClient.SqlParameter("@ProcessName", Data.SqlDbType.NVarChar)
46               param.Value = PNameTxt.Text
47               cmd.Parameters.Add(param)
49               param = New Data.SqlClient.SqlParameter("@ProcessPGU", Data.SqlDbType.NVarChar)
50               param.Value = PPGUDDL.SelectedValue
51               cmd.Parameters.Add(param)
53               param = New Data.SqlClient.SqlParameter("@EntityBelongTo", Data.SqlDbType.NVarChar)
54               param.Value = EntityDDL.SelectedValue
55               cmd.Parameters.Add(param)
57               param = New Data.SqlClient.SqlParameter("@TeamBelongTo", Data.SqlDbType.NVarChar)
58               param.Value = TeamDDL.SelectedValue
59               cmd.Parameters.Add(param)
61               param = New Data.SqlClient.SqlParameter("@ProcessMap", Data.SqlDbType.VarChar)
62               param.Value = "~/PMap/Main/" & PMapFU.FileName
63               cmd.Parameters.Add(param)
65               param = New Data.SqlClient.SqlParameter("@ProcessOwner", Data.SqlDbType.NVarChar)
66               param.Value = POwnerTxt.Text
67               cmd.Parameters.Add(param)
69               param = New Data.SqlClient.SqlParameter("@CurrentVersion", Data.SqlDbType.Decimal)
70               param.Value = CurrentVerTxt.Text
71               cmd.Parameters.Add(param)
73               param = New Data.SqlClient.SqlParameter("@VersionDate", Data.SqlDbType.DateTime)
74               param.Value = VerDateTxt.Text
75               cmd.Parameters.Add(param)
77               param = New Data.SqlClient.SqlParameter("@FirstIssueDate", Data.SqlDbType.DateTime)
78               param.Value = FIDateTxt.Text
79               cmd.Parameters.Add(param)
81               param = New Data.SqlClient.SqlParameter("@PreparedBy", Data.SqlDbType.NVarChar)
82               param.Value = PreparedByTxt.Text
83               cmd.Parameters.Add(param)
85               param = New Data.SqlClient.SqlParameter("@ApprovedBy", Data.SqlDbType.NVarChar)
86               param.Value = ApprovedByTxt.Text
87               cmd.Parameters.Add(param)
89               param = New Data.SqlClient.SqlParameter("@Purpose", Data.SqlDbType.NVarChar)
90               param.Value = PurposeTxt.Text
91               cmd.Parameters.Add(param)
93               param = New Data.SqlClient.SqlParameter("@Description", Data.SqlDbType.NVarChar)
94               param.Value = DescTxt.Text
95               cmd.Parameters.Add(param)
98               cnn.Open()
99               cmd.ExecuteNonQuery()
100              cnn.Close()
102              SaveMsg.Text = PNameTxt.Text + " is saved!"
103              Return
104          Catch
ex As Exception
105              SaveMsg.Text = ex.Message.ToString
106          End Try
108      End Sub




12/26/2007 4:03:29 AM

 Hi SummerBreez, can you post the browse file uploadcode that matches the above code behind? I'd love to look at it!! Thanks!

8/8/2008 11:03:16 PM

Similar Artilces:

Displaying image from database(image datatype) to image control
Hie all...I'm a newbie at I m currently using 2.0.I m having a problem with displaying images on my web form. Have tried looking thru all codes but i can't find a step by step tutorial for doing so. I understand that in 1.1, the detailsview can automatically be linked to the image field and display the image. But this is not possible now. So, i have decided to just display the image in an image control.from my understanding, 1. retrieve image from database and convert it to temporary image file in a file path. 2. use the image control's imageurl to point to the file....

Thumbnail image to popup Fullsize image (image paths from a database)
I am trying to modify an example of code from  - - >  Image Scripts - - > Image Gallery 7 (Reusing popup for large image)   where instead of using the hardcoded image in the example javascript, I can reference the path to that image which is loaded in my Access DB.   I was able to modify the HTML img to find the src of the thumbnail path. So too is the path to the full image located in my Access DB.   Is there a way I can load the path to the full image in the javascript or does anyone ...

how to check image path is not present & display some other image while using gridview
hi,I just store image name in table.I display image in grid using<asp:image id="Image1" runat="server" imageurl='<%# Eval("photopath", "~/propertyimages/{0}") %>' />  i want to check if image is present in that row..if not i want to display some default image.How can i do so? Please Mark the post as "ANSWER" if it helps you   Give this a shot, it will fire a method in the code behind that returns the image url if the image exists and a default image if it doesn't exist <asp:image id="Image1&q...

retrieving images from database and displaying on Image control
Hi all i need a solution for displaying an image which must be retrieved from database table(photo displaying).I used the following code,but it shows error as "Invalid Parameter used"   page_load() {   cn.Open ();        SqlCommand command = new SqlCommand ("select *from image1 ", cn);                                 byte[] image = (byte[])( command.ExecuteScalar());     &n...

display image in a image image button
hi   i have to display an image in image button while uploading mycode Image1.ImageUrl = Upload.PostedFile.FileName; is not working thanks Hi You need to save the PostedFile to the disk on the server and then assign it to ImageUrl. Take a look at the following links for more infoprmation on how to do this. Nassabehwww.professionalcsharp.comDon't forget to click "Mark as Answer" on the post that helped you. That way ...

Problems with a thumbnail image to popup Full-size image (image paths from a database)
I am hoping to get more feedback from entering this in perhaps a more appropriate forum.   Please refer to post   I think I’ve explained what I would like to do but can’t figure out how to successfully code it.   I found it interesting that if I removed the Onclick event, my Bind error goes away.   And changing the Bind to an Eval traded the Bind error for a parser error.   How can I pass the path of the Full size image from my DB to the javascript so that ASP and Java both are OK with the coding?  ...

How to retrieve path of an image which is stored as image data in database.
Hi there, Is there anyone who can solve my problem? I need to use SlideshowExtender for photo album. As all know, to achieve this, there is a class called "Slide" in "AjaxControlToolkit" namespace, and "Slide" class takes (imagePath As String, name As String, description As String). I am uploading images as a binary data type in database and i am able to achieve those images as image object. Now my problem is how to pass "imagePath" in "Slide" class. Can anyone help?  Thanks in advance - Prachi Friend, I would recommend yo...

Image on Image
I am trying to display a page that has image of a map on it. The user can then place other images of red thumbtacks on the image at different locations. Then when these thumb tacks are clicked on, they open a folder of pics related to the area. I saw a method in the imageButton class that returns the (x,y) of the location where the user clicked. I thought I could use this information to place another, smaller image button, on that area. My problem is that i can't seem to get the bottom imageButton to be transparent so I can see the smaller one. Am i on the right track with this. Any advi...

Image in image
Hi, I have a project where clients viewing my website can buy t-shirts. They can choose from a number of t-shirt colors and shapes which are their plain colour. They can also choose a number of prints to be placed on the t-shirt. These will be graphics stored in a database. My problem is on how I can displaty the t-shirt with the graphics or logo they chose on te t-shirt. It would be something like drawing text on an image but instead drawing an existing image on the base image. Any Ideas? (I am using visual studio 2005 and vb.NET)   RegardsMerovingian you 1. You can create a...

Imaging, but not imaging
We multicasted to 43 machines. Updated the image on the master. Multicasted the updated image to 36 machines. (the other 7 wouldn't join the session for some unknown reason). I visually verified that all 36 were imaging. One of the 8 which didn't rename appears to not even have been imaged. The problems with the previous image were still there. It's as though the machine didn't image even though I saw it take part in the session and the temp bar going across the screen. What the heck's going on here? AlaN As a try, what happens if you boot either to PXE ...

image and image
// create an image object, using the filename we just retrieved System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(file)); // create the actual thumbnail imageSystem.Drawing.Image thumbnailImage = image.GetThumbnailImage(64, 64, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);   now my question is how to display this image in my image1 control in (version 1.1) the below line of code is not working.  Image1.ImageUrl=thumbnailImage.ToString();Mark As Answer If my reply helped you. Hi, you can save t...

Display image in image control from database?
Im looking for how to load an image in a database into an image control. I would like to be able to display images with assocated image captions in a page stored in a database. Samples I have found only deal with writing out the binary data directly into the page. Does anyone have a link on how to associate that image data in the database with an image control on the page? Have a look at this control in the control Gallery.  Should do what you want.JamesMy Blog: I found a few articles on this such as, http://blogs.ww...

Display Image from database in an Image control
I have uploaded images to a database and now I want to display the images in an image control.  How do I do it?  Any help is appreciated. ThanksMark post(s) as "Answer" that helped youElectronic ScrewWebsite||Blog|| I've read the article before and it is not what I'm looking to do, only half of what I'm looking to do.  I need to retrieve the data information from a database and bind the image to an image control not a datagrid or gridview or datalist, a label control. Its literally it tho...

retrving image from the image path in the database.
hi . i am storing the image path in the database.i have 2 colums id, path1 D:\project\bank\adsai.jpg2 D:\project\bank\ads34ai.jpg3 D:\project\bank\a4ai.jpgnow i need retrive image . once the user enter 2 he needs to get that image for the id 2. ans so to retrive the image and display in an imagecontrol prince5: hi . i am storing the image path in the database.i have 2 colums id, path1 D:\project\bank\adsai.jpg2 D:\project\bank\ads34ai.jpg3 D:\project\bank\a4ai.jpgnow i need retrive image . once the user enter 2 he needs to get that image for the id 2. ans so to retrive...

Web resources about - Save Image Path into Database, Retrieve Image Path by Particular Image ID and Display Image through Gridview -

Michael Caine Weighs In Oscars Boycott – Confused About Idris Elba Snub, Claims Black Actors Need To ...
Lack of diversity among the Oscar nominations has become a huge theme again, as the Academy Awards heads into their second year with no black ...

iPhone 5se Could Be New 4-Inch Handset
We all more or less know that there is going to be a new iPhone every single year, at least that has been the trend since 2008, but the question ...

This Weekend's Storm Will Be a Bizarre Mix of Floods, Ice, Wind, and Up to Three Feet of Snow
The great storm is finally here. What can we expect? The latest forecast is out—and it’s both weird and grim. Read it tucked safely indoors, ...

EPA Worker Details Discovery of Flint's Contaminated Water
A concerned mom and a diligent EPA worker helped uncover the find.

Editorial Cartoons: Stock market, China and oil prices
In this slideshow, we illustrate through cartoons the struggles on Wall Street the past few weeks and the main culprits are actually taking place ...

The Latest: Armed Group's Leader Refuses Private FBI Talk
The leader of an armed group occupying a national wildlife refuge in Oregon met briefly with a federal agent but left because the official wouldn't ...

How Apple’s VR hire leads to a gesture-controlled car
Apple reported to hire Doug A Bowman, a virtual reality specialist, 3D interface specialist, and computer science professor at Virginia Tech. ...

Former Oklahoma City police officer sentenced to 263 years in prison
An Oklahoma County judge Thursday sentenced a fired Oklahoma City police officer convicted last month of on-duty rapes to 263 years in prison. ...

Microsoft Finally Resolving A Five-Year-Old Skype Privacy Flaw For All Users
There’s a security flaw in Skype that can expose users’ location. That’s not the news, though: that flaw was discovered in 2010, and published ...

Here's how to get a free Microsoft Surface Pro power cord replacement
Microsoft has announced a voluntary replacement program for all Surface Pro tablet AC power cords sold before March 15, 2015 in the United States ...

Resources last updated: 1/22/2016 11:00:27 PM