3
Answers

storing and retriving images in database reg

Gowtham manju

Gowtham manju

13y
2.8k
1
hi,

i need to store the images in database and retrive it through asp.net with c#.

these are given as

Query :

create database sss
go
use sss
go
create table ss_imgsample(imgid int identity(1,1),imgname varchar(150),imgfile image,primary key(imgid))
go
select * from ss_imgsample
go






Design :

<div style="height: 361px">
file name :
<asp:TextBox ID="TextBox1" runat="server">
<br />
choose the image file
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="click" />
<br />
<br />
<asp:Label ID="Label1" runat="server">
<br />
<asp:Label ID="Label2" runat="server">
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="imgid" DataSourceID="SqlDataSource1">

<asp:BoundField DataField="imgid" HeaderText="imgid" InsertVisible="False"
ReadOnly="True" SortExpression="imgid" />
<asp:BoundField DataField="imgname" HeaderText="imgname"
SortExpression="imgname" />


<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:sssConnectionString %>"
SelectCommand="SELECT * FROM [ss_imgsample]">
</div>






Coding :

using System.Data.SqlClient;

SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sss;Integrated Security=True");
SqlCommand cmd = new SqlCommand();


protected void Button1_Click(object sender, EventArgs e)
{
attach();
}
protected void attach()
{
lbl_attachments.Text = "";
try
{
if (FileUpload1.HasFile)
{
Label1.Text = fileupload_img.FileName;
FileUpload1.SaveAs(Server.MapPath("~/Tempfiles/" + Label1.Text));
cmd = new SqlCommand("insert into ss_imgsample values('" + TextBox1.Text + "','" + FileUpload1.PostedFile.FileName + "') ", con);
if(cmd.EndExecuteNonQuery()>0)
{
Label1.Text="inserted";
}else{
Label1.Text="not done";
}

}
else
{
Label1.Text = "No file selected";

}
}
catch (Exception ex)
{ Response.Write(ex.Message); }

}



--------------------------------------


we have to insert the value in to database and show the value in grid view.
if u click on the grid view image then the page is redirected ti new page and displays the file name and image.


can any one help me to solve this

waiting for ur response.

responces highly appreciated


Answers (3)