How to Insert the Image URL into Sql database and display that particular Image of the URL in GridView

 How to Insert the Image URL into Sql database instead of storing the original image itself and display that particular Image of the URL dynamincaly in GridView.

For example for each product there will be one image ,here i want to store that Image URL (locally/in other Links) into the Sqldatabase and on selecting for

an particalur product id i want it to display that image of the product in Grid View.How can i proceed........?

i am seeking for help. 

 

0
sandynaidu
3/2/2008 1:21:28 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

6 Replies
1446 Views

Similar Articles

[PageSpeed] 52

If I understood you question this is not very hard

1.  Created a table id, description and ImgUrl.  The ImgUrl field is a nvarchar(max)

2.  I inserted urls into that field. I did this by adding a folder to my project call Images and collected some images and threw them in there

3.  I populated the table with the respective url's text (path)

4.  Added a Gridview and used a SQLDATASOURCE

 

HERE IS THE CODE

page markup

 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="InsertImageUrls.aspx.vb" Inherits="InsertImageUrls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" 
            CellPadding="4" DataKeyNames="id" DataSourceID="SqlDataSource1">
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <RowStyle BackColor="White" ForeColor="#003399" />
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" 
                    SortExpression="id" />
                <asp:BoundField DataField="Description" HeaderText="Description" 
                    SortExpression="Description" />
                <asp:BoundField DataField="ImageUrl" HeaderText="ImageUrl" 
                    SortExpression="ImageUrl" />
                <asp:ImageField DataImageUrlField="ImageUrl" HeaderText="Image">
                </asp:ImageField>
            </Columns>
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:AcmeDataConnectionString %>" 
            SelectCommand="SELECT [id], [Description], [ImageUrl] FROM [ImageBank]">
        </asp:SqlDataSource>
        <asp:LinkButton ID="LinkButton2" runat="server" 
            PostBackUrl="~/Images/Sunset.jpg">LinkButton</asp:LinkButton>
    </div>
    </form>
</body>
</html>
  

code behind

Partial Class InsertImageUrls
    Inherits System.Web.UI.Page

    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged
        ' Nothing!!
    End Sub
End Class

 A bit of explanation

I used an ImageField and binded  DataImageUrlField="ImageUrl" if you look at the markup you will notice that ImageUrl is the previouly defined field. this will display the image in the grid from the boundfield without add the Image to the database

 

In  GridView1_SelectedIndexChanged you could add code to do whatever you wish It.

Have fun and good luck

 

  
I am not anti social, am just not user friendly
0
aamador
3/2/2008 3:02:51 PM

have a look at the following tutorials :

http://msconline.maconstate.edu/tutorials/ASPNET2/ASPNET07/aspnet07-02.aspx

http://msdn2.microsoft.com/en-us/library/aa479350.aspx

 

 


Regards,

Anas Ghanem.


Note:Please Don't hesitate to click "Report Abuse" link if you noticed something wrong on the forums (like duplicate ,Off-topic,offensive,or any post that violates the website "TERMS OF USE"). -- Thanks!

0
anas
3/2/2008 3:04:36 PM

Forgot one thing!! I tested this and is working so if you like the code I can make it available but is so simple you could write something in SqlServer, Oracle or whatever your using really quick. and there is no real code so.

Let me know.


I am not anti social, am just not user friendly
0
aamador
3/2/2008 3:05:56 PM


Hey sandynaidu,

You'll need the following to make this sample works:  

0 - Label [ lblResult ]
1 - Change the connectionString 
2 - Change the Class Name
3 - Button [ btnAdd ] 
4 - GridView 
5 - SqlTable [ products ]

Table Products :

productID     int [ identity ]
productName     nvarchar(100) 
productPrice nvarchar(100) 
productImg     nvarchar(500) 
  

Then Please, do the following

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

SqlConnection conn = new SqlConnection("Data Source=XGMARX\\SQLEXPRESS;Initial Catalog=linksTest;Integrated Security=True;Pooling=False");

protected void Page_Load(object sender, EventArgs e)

{

if (!this.IsPostBack)

{

GridView1.DataSource = getProducts();

GridView1.DataBind();

}

 

}

protected void btnUpload_Click(object sender, EventArgs e)

{

if (FileUpload1.HasFile)

{

// Call a helper method to save the file.

SaveFile(FileUpload1.PostedFile);

}

else

{

lblResult.Text =
"Error, no file inserted.";

}

}

 

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

Image1.Visible =
true;int productID = Convert.ToInt32(GridView1.SelectedDataKey["productID"].ToString());

Image1.ImageUrl = getProducts(productID);

}

void SaveFile(HttpPostedFile file)

{

// Specify the path to save the uploaded file to.

string savePath = Server.MapPath("archive/");

// Get the name of the file to upload.

string fileName = FileUpload1.FileName;

// Create the path and file name to check for duplicates.

string pathToCheck = savePath + fileName;

// Create a temporary file name to use for checking duplicates.

string tempfileName = "";

// Check to see if a file already exists with the

// same name as the file to upload.

if (System.IO.File.Exists(pathToCheck))

{

int counter = 2;

while (System.IO.File.Exists(pathToCheck))

{

// if a file with this name already exists,

// prefix the filename with a number.

tempfileName = counter.ToString() + fileName;

pathToCheck = savePath + tempfileName;

counter++;

}

fileName = tempfileName;

// Notify the user that the file name was changed.

lblResult.Text = "<br />A file with the same name already exists." + "<br />Your file was saved as " + fileName;

}

else

{

// Notify the user that the file was saved successfully.

lblResult.Text = "Your file was uploaded successfully.";

}

// Append the name of the file to upload to the path.

savePath += fileName;

// Call the SaveAs method to save the uploaded

// file to the specified directory.

FileUpload1.SaveAs(savePath);

 

String sqlInsert = @"insert into products (productName, productPrice, productImg)

values (@productName, @productPrice, @productImg)";

SqlCommand comm = new SqlCommand(sqlInsert, conn); comm.Parameters.AddWithValue("@productName", fileName);

comm.Parameters.AddWithValue("@productPrice", "10000$");

String []imgPath = savePath.Split('\\');

comm.Parameters.AddWithValue("@productImg", imgPath[imgPath.Length - 2] +"\\"+ imgPath[imgPath.Length-1]);

conn.Open();

comm.ExecuteNonQuery();

conn.Close();

GridView1.DataSource = getProducts();

GridView1.DataBind();

}

private DataTable getProducts()

{

String sql = @"select productID, productName, productPrice, productImg from products";

SqlCommand comm = new SqlCommand(sql, conn);

SqlDataAdapter adptr = new SqlDataAdapter(comm);DataSet ds = new DataSet();

adptr.Fill(ds);

return ds.Tables[0];

}

private String getProducts(int productID)

{

String imgLink;

String sql = @"select productImg from products where productID = @productID";

SqlCommand comm = new SqlCommand(sql, conn);

comm.Parameters.AddWithValue("@productID", productID);

SqlDataAdapter adptr = new SqlDataAdapter(comm);

DataSet ds = new DataSet();

adptr.Fill(ds);

imgLink = ds.Tables[0].Rows[0][0].ToString();

return imgLink;

}

}

 

 

and this is the aspx page 


 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>FileUpload Control Sample</title> </head>

<body>

<form id="form1" runat="server">

<div>

&nbsp;<asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID="btnUpload" runat="server" Height="20px" OnClick="btnUpload_Click"

Text="Upload" />

<asp:Label ID="lblResult" runat="server"></asp:Label><br />

<br />

&nbsp; &nbsp;

<table border="0" cellpadding="0" cellspacing="0">

<tr>

<td style="width: 136px; height: 152px">

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" DataKeyNames="productID">

<Columns>

<asp:TemplateField HeaderText="Product Name" ShowHeader="False">

<ItemTemplate>

<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Select"

Text="<%# Bind('ProductName') %>"></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Product Price">

<EditItemTemplate>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID="Label1" runat="server" Text="<%# Bind('productPrice') %>"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

</td>

<td style="width: 29px; height: 152px" valign="top">

<asp:Image ID="Image1" runat="server" Visible="False" Height="177px" Width="189px" /></td>

</tr>

</table>

 

</div>

</form> </body>

</html>

It worked with me...

Please, let me know if that helped ...

Best Regards ...


Please, “Mark as Answer” the post that helped you.
0
XGmarX
3/2/2008 5:25:30 PM

Thanx for your example and its working fine but i tried to access through the .cs when i debug this i am not able to find the data Grid but only the Link button is visible der.What might be the wrong?

here is my .aspx page

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Copy of ImageGrid.aspx.cs" Inherits="ImageGrid" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
            CellPadding="4" DataKeyNames="id"  OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <RowStyle BackColor="White" ForeColor="#003399" />
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True"
                    SortExpression="id" />
                <asp:BoundField DataField="Description" HeaderText="Description"
                    SortExpression="Description" />
                <asp:BoundField DataField="ImageUrl" HeaderText="ImageUrl"
                    SortExpression="ImageUrl" />
                <asp:ImageField DataImageUrlField="ImageUrl" HeaderText="Image">
                </asp:ImageField>
            </Columns>
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
        </asp:GridView>
       
        
        <asp:LinkButton ID="LinkButton1" runat="server"
            PostBackUrl="~/Image/Sunset.jpg">LinkButton</asp:LinkButton>&nbsp;

    </div>
    </form>
</body>
</html>

here is my .cs page

 using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ImageGrid : System.Web.UI.Page
{
    static string connection = System.Configuration.ConfigurationManager.ConnectionStrings["usercon"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand("SELECT [id], [description], [ImageUrl] FROM [ImageBank]", con);
        con.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();
        con.Close();
    }
}

can u please recitify the mistake i have done

0
sandynaidu
3/3/2008 7:51:11 AM


 

Hey sandynaidu,


1 - Dont forget to remove the "Auto-Generate Field" incase you're using the templateField

2 - You're missing the binding part.

<asp:TemplateField HeaderText="Product Name" ShowHeader="False">

<ItemTemplate>

<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Select"

Text="<%# Bind('Description') %>"></asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>

 

BTW, you dont need to have a column for the img if you want to display one @ SelectedIndexChanged..

1 - make a table of 1 row and 2 columns

2 - put the grid into the 1st column

3 - put the img control into the 2nd column

4 - Configure it using the way posted be4   [ I've edited the post ]

 

Please, let me know if that helped ...

Best regards ...


Please, “Mark as Answer” the post that helped you.
0
XGmarX
3/3/2008 3:56:50 PM
Reply:

Similar Artilces:

How to Insert Image Url and Display the Image of that Image Url in the Grid View?
Any one can help me out about this- How to Insert Image Url and Display the Image of that Image Url in the Grid View Hi You can add HyperLink control to Gridview by setting its ImageUrl and NavigationUrl property Please refer example. <asp:HyperLink ID="HyperLink1" ImageUrl="images/image.gif" NavigateUrl="PageUrl.aspx" runat="server">HyperLink</asp:HyperLink>Please mark the post as answered if it helped you. Hi sandynaidu, This is easy to solve. Assuming that your GridView's ID is gv, that you want to have the image in your firs...

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 pro...

Storing images in SQL database vs storing images in seperate folder and using URL image path
Hi allCan you store images in a sql database and if so, does it store the images as an image file or does it store it in a binary format reducing the size of the image. If it can be stored in an sql database as a image or a binary format what are the advantages/disadvantages or is it better to store the url in the database and then bind the image holder to the url link in the database. Hi, These two ways are both ok. My suggestion is to store images into sql database if there are no much more images, otherwise, it's better store them into file system because you can store them no mat...

Displaying image from database(image datatype) to image control
Hie all...I'm a newbie at asp.net. I m currently using asp.net 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 asp.net 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....

display image in Gridview from sql image in .Net 2005
Hi all, I need to Display the Image directly from SQL Database in the GridView as Thumnails. This i can do in .Net 2003 with Help of ItemDatabound Event and Template Column. But in the .Net 2005 there no ItemDatabound event in GridView. For Example I need to Show it like this:  Help Me ASAP.Tamil See :http://www.beansoftware.com/ASP.NET-Tutorials/Images-Database.aspxHope this helps. Vikram.S, DeveloperDiscountASP.NETInnovative ASP.NET Hosting & SQL Hosting Thanks a lot Sharma. It was very useful.  Tamil...

SQL image URL, display in gridview
In my website I have a folder called ’Pictures’, with subfolders e.g ’Projects’. I want to be able to organize (link) my pictures in a SQL database, and later display the pictures. In the SQL table called ‘Pictures’ I type the link to the picture residing in the Pictures folder, eg: ‘~/Pictures/Projects/test.jpg’, in a varchar column.  However, when I create a gridview to display the pictures, it will display the table fields (PictureID, PictureLink, etc) correctly, but the PictureLink field does not display the actual pictures, only ...

How to display the image in an image control as url from server D: drive
Hi, I am using an image control to display some images My Issue is I need to take the image url from D drive of server Is any body have the code to get the imageurl from the server, Other than the project folder The code I used is Dim path As String = "F:\Images\boy.bmp" Image1.ImageUrl = Server.MapPath(path) Thanks, You can not access the files out side of you website root directory....Chinna_sv......

Displaying image in GridView - direct from database
I would really appreciate a lot if someone could put me in the right direction with my - actually really simple problem.I want to display an image in GridView directly from an SQL database field. The field contains the image itself, not only the URL to the image.We didn't had it in 1.0, then Microsoft included in Visual Studio Beta 1, then they took it away again in Beta 2 and also in Release Candidate - and I cant found anything wher they documented why they took it away.That is why the large part of the examples I have found (in the last two weeks now :-( ) contains code and an explanation...

How to display the image in an image control as url from server D: drive #2
Hi, I am using an image control to display some images My Issue is I need to take the image url from D drive of server , Other than the project folder The code I used is : Dim FileName As String = "boy.gif" If FileName IsNot Nothing Then Try ' Read the file and convert it to Byte Array Dim filePath As String = "C:\images\" 'FileName = Request.QueryString("FileName") Dim contenttype As String = "image/" & Path.GetExtension(FileName).Replace(&...

Image url for Gridview control whose url depends on data element
I currently have a gridview that is bound to a webservice. I can add a select hyperlink in the gridview that will pass the primary key for the selected row to the next page to get the details. I would like the select to be an image, however the image would be determined base on a value that is returned from the webservice. Example: I would like an image of Car if the itinerary type is "C". And I would like a plane if the itinerary type is "A". Here is my current code.   <asp:GridView ID="ItineraryGridView" runat="server" CellPadding="4" ForeColor="#333333" GridLines="Horizont...

how to save image on server and add image url to database for display on web page
I am trying to figure out how to allow a user to insert a new record into the database with the option of adding an image to the item.  The picture would then be saved on a web server and the link to the picture would be saved in a column of the table.  I would then need to display the picture along with its other information such as a description when the user selects the record from a drop down list on the page.  I have been searching everywhere and cannot find a good guide to help me accomplish this.  Can someone please help me?   There are a bunch of starter k...

Displaying image in a gridview using its URL stored in a database
Hi there, I don´t know if I'm posting in the right place... I need help in trying to display images in a gridview. I have the url of my images stored in a database and I want to use it to show them in the gridview. I'm also trying to do this all in C# code. I've seen some examples and all show how to do this but with the image binary stored in the database.  I'm really needing some help.  Thanks  You can use the default grid view image field like this:   <asp:ImageField DataImageUrlField="ThumbUrl" HeaderText="Image" /> &...

Display image in image control from database?
Im looking for how to load an image in a database into an asp.net 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: http://www.wintersfamily.plus.com/blogs/JamesWinters 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. http://aspalliance.com/articleViewer.aspx?aId=140 ThanksMark post(s) as "Answer" that helped youElectronic ScrewWebsite||Blog||Dub@i.net 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...

Web resources about - How to Insert the Image URL into Sql database and display that particular Image of the URL in GridView - asp.net.presentation-controls

The Latest: Brussels official: City still faces grave threat
BRUSSELS (AP) — The latest on the deadly attacks in Paris and the heightened security in Europe (All times local):

Obama administration assures dissenting governors on refugee vetting
The Obama administration is assuring governors that refugees who come to the United States in its resettlement program undergo a “rigorous security ...

Democrats celebrate victory in Louisiana governor's race
NEW ORLEANS (AP) — Democrats in Louisiana rejoiced as they reclaimed the governor's mansion for the first time in eight years, while the state's ...

Bronx woman, 22, charged with stabbing expectant mother to death: NYPD - New York's PIX11 / WPIX-TV
THE BRONX– Police have arrested a 22-year-old woman who stabbed an expectant mother to death in her Bronx apartment yesterday afternoon. Ashleigh ...

Justin Bieber’s Exes: One On Tinder, Another Reveals She’s 6 Months Pregnant
Justin Bieber’s new album “Purpose” awaits its official release in just a matter of days, while Biebs has already made available a half dozen ...

No. 9 Michigan State beats No. 2 Ohio State 17-14 on late FG
COLUMBUS, Ohio (AP) — The last place Michael Geiger, all 5-foot-8 and 185 pounds of him, wanted to end up was at the bottom of a pile of Michigan ...

John Hancock Center Fire Extinguished, 5 People Injured Downtown
DNAinfo John Hancock Center Fire Extinguished, 5 People Injured Downtown (VIDEO) DNAinfo CHICAGO — Five people were injured, including one ...

ASEAN creates new economic community that’s larger than EU
Prime Minister Narendra Modi was in the audience, seated next to his Chinese counterpart Li Keqiang, as 10 leaders of the Association of Southeast ...

Realism in Fighting the Islamic State
After a bloody series of terrorist attacks, the natural impulse is to respond with overwhelming force to make sure they never happen again. The ...

Former South Korean President Kim Young-sam Dies at Age 87
NBCNews.com Former South Korean President Kim Young-sam Dies at Age 87 NBCNews.com SEOUL, South Korea — Former President Kim Young-sam, who ...

Resources last updated: 11/22/2015 12:39:16 PM