Hello
friends
In this article, we will explore how to store
images in the database and then display those images along with the other
server controls
Today I
am going to show how you can save image
from web page to database using asp File Upload Control and retrieve same image . There might be various
approaches for this I am going show one of them
Using
handlers : by converting image into binary format
I am going to a build a form, with the person’s
details and his photo along with it, or for that case, display the image in an
ASP.NET server control along with other controls?
Let us start off by first creating a
sample database and adding a table to it. We will call the database and the
table will be called ‘Tbl_Emp’
Database
structure will be like this
Step 1: Create a new asp.net website and add
a webpage to it
Step2: Drag and drop two textbox controls. Also drag
drop a File Upload control and two button control to upload the selected image
on button click and to retrieve record from database. Dropdown List to select
list ID which will be used to retrieve selected record from database
Aspx page code will look like below
<div>
Enter ID
<asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox><br />
Enter Name <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
Enter Pic
<asp:FileUpload ID="FileUpload1"
runat="server"
/><br />
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" /><br >
<asp:Image ID="Image1"
runat="server"
Height="137px"
Width="130px"
/><br />
<asp:DropDownList ID="TextBox3" runat="server">
</asp:DropDownList>
<asp:Button ID="Button2" runat="server" Text="Search" onclick="Button2_Click" />
</div>
Step3: code on .cs page
On my code there are three methods
Filldropdown() : used to fill dropdown
Button1_Click : used to save image into database
Button2_Click : used to retrieve image from
database
static SqlConnection
con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated
Security=True;User Instance=True");
protected void
Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
filldropdown();
}
}
public void
filldropdown()
{
SqlCommand cmd = new
SqlCommand("Select
EmpID from Tbl_Emp", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
TextBox3.Items.Clear();
if (dr.HasRows)
{
//TextBox3.DataSource = dr["EmpID"].ToString();
//TextBox3.DataBind();
while (dr.Read())
{
TextBox3.Items.Add(dr["EmpID"].ToString());
}
}
con.Close();
}
protected void
Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new
SqlCommand("insert
into Tbl_Emp values(@id,@name,@image)",con);
cmd.Parameters.AddWithValue("@id",
TextBox1.Text);
cmd.Parameters.AddWithValue("@name",
TextBox2.Text);
int img = FileUpload1.PostedFile.ContentLength;
byte[] msdata = new byte[img];
FileUpload1.PostedFile.InputStream.Read(msdata,0,img);
cmd.Parameters.AddWithValue("@image",
msdata);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd.ExecuteNonQuery();
con.Close();
filldropdown();
Response.Write("Data Saved ....");
}
protected void
Button2_Click(object sender, EventArgs e)
{
SqlCommand cmd = new
SqlCommand("select
* from Tbl_Emp where EmpID=@id", con);
cmd.Parameters.AddWithValue("@id",
TextBox3.Text);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows && dr.Read())
{
TextBox1.Text = dr["EmpID"].ToString();
TextBox2.Text = dr["EmpName"].ToString();
Image1.ImageUrl = "Handler.ashx?EmpID="
+ TextBox3.Text;
}
else
{
Response.Write("Record With This ID
Note Found");
}
}
Step 4: In order to display the
image on the page, we will create an Http handler. To do so, right click
project > Add New Item > Generic Handler > Handler.ashx. The code
shown below, uses the Request.QueryString[“id”] to retrieve the EmpID from it.
The ID is then passed to this handler
from drop on button 2 click
<%@ WebHandler
Language="C#"
Class="Handler"
%>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
public class Handler : IHttpHandler
{
static SqlConnection
con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated
Security=True;User Instance=True");
public void
ProcessRequest (HttpContext context) {
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
SqlCommand cmd = new
SqlCommand("select
EmpPic from Tbl_Emp where EmpID=@EmpID",con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd.Parameters.AddWithValue("@EmpID",
context.Request.QueryString["EmpID"].ToString());
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows && dr.Read())
{
context.Response.BinaryWrite((byte[])(dr["EmpPic"]));
}
con.Close();
}
public bool
IsReusable {
get {
return false;
}
}
}
I hope this article was
useful
You can download complete
code from this link Download Code
in next i am going to show how you can display all images in GridView Display Images in GridVIew
in next i am going to show how you can display all images in GridView Display Images in GridVIew
great artical...thank u very much .finally my problem solved...
ReplyDeleteI m getting Instance failure error??
ReplyDeletehw can remove..it;
in line
con.open()
hello
DeleteDeepak
Try this steps
1. Stop all user instance processes of SQL Server running under your local account (open up task manager and look for sqlsrv.exe process and end it)
2. Delete all files in the %LOCALAPPDATA%\Microsoft\Microsoft SQL Server Data\SQLEXPRESS folder
3. F5 again
and chnage connection string
private static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
Thnxx Manish for reply and i also caught error..i completed it using web.config file. Thnxx for this important artical.
ReplyDeleteHi,
ReplyDeleteI've got to save file that is choosen using fileupload control to the ms sql database (tbl_Material with columns as name, path, workshopTile FK).
also the file choosen should only be in the zip format.
what should be the code in c#. I want to use the strongly typed datasets.
Please help as I'm a beginner in learning asp.net
hey
Deleteif(FileUploadControl.PostedFile.ContentType == "zip")
{
// write your file uploading code here
}
you can refer this link
http://asp.net-tutorials.com/controls/file-upload-control/
Hi manish,
DeleteThanks for your reply. Can I have the code for storing those files via strongly typed datasets?
image is not appearing what is the reason for it ?? pls help
ReplyDeleteif you have downloaded the same sample update you connection string with this
Deletestatic SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
bvcvm,n.m
Deletemy image is not showing, though i have the correct data source anf provider written correctly. i am using access database but the image is not showing and there was no error, pls help me
ReplyDeleteVery thanks,,I got the solution from you
ReplyDeleteThank u
ReplyDeletehi ,manish,,
ReplyDeletei have a error that is --"create instance for new object" on int position...plz..help me
thanx a lot :)
ReplyDeleteJQuery Validation in ASP.NET Master Page
ReplyDeletehttp://allittechnologies.blogspot.in/2015/04/how-to-validate-aspnet-master-page-control-using-jquery.html
thanks it works well god bless your days man
ReplyDeleteSave and Retrieve image from Database and Display in Gridview or list of image in Panel
ReplyDeleteSave and Retrieve Image from Database and Display in Gridview or Panel
i saved my image in folder of solution explorer with userid,now i want to show each image with user in gridview, how i can show. Please reply me . My email id is mukeshkamboj28@gmail.com
ReplyDeleteGreat post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
ReplyDeleteautomation anywhere training in chennai
automation anywhere training in bangalore
automation anywhere training in pune
automation anywhere online training
blueprism online training
rpa Training in sholinganallur
rpa Training in annanagar
iot-training-in-chennai
blueprism-training-in-pune
automation-anywhere-training-in-pune
I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.
ReplyDeleteData Science Training in Chennai
Data science training in bangalore
Data science online training
Data science training in pune
Data science training in kalyan nagar
selenium training in chennai
I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true. . .
ReplyDeletejava training in marathahalli | java training in btm layout
java training in jayanagar | java training in electronic city
java training in chennai | java training in USA
selenium training in chennai
I have been meaning to write something like this on my website and you have given me an idea. Cheers.
ReplyDeletepython training in tambaram
python training in annanagar
python training in OMR
python training in chennai
A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
ReplyDeleteBlueprism training in annanagar
Blueprism training in velachery
Blueprism training in marathahalli
Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
ReplyDeleteangularjs Training
in chennai
angularjs Training in chennai
angularjs-Training in tambaram
angularjs-Training in sholinganallur
angularjs-Training in velachery
Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
ReplyDeleteSap Mm Training From India
I am really happy with your blog because your article is very unique and powerful for new reader.
ReplyDeleteClick here:
selenium training in chennai
selenium training in bangalore
selenium training in Pune
selenium training in pune
Selenium Online Training
https://skdotnetdeveloper.blogspot.com/2011/09/send-sms-in-cnet.html
I want to thank for sharing this blog, really great and informative. Share more stuff like this.
ReplyDeleteMachine Learning course in Chennai
Machine Learning Training in Chennai
Data Science Course in Chennai
UiPath Training in Chennai
Azure Training in Chennai
Angularjs Training in Chennai
ReactJS Training in Chennai
A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out til the end.
ReplyDeletedevops online training
aws online training
data science with python online training
data science online training
rpa online training
Very impressive thanks for sharing
ReplyDeleteDevOps Training in Chennai
DevOps Certification in Chennai
Salesforce Training in Chennai
Wonderful Blog post, great article that you have provided for peoples. Its really good. Nice information.
ReplyDeleteData Science Courses in Bangalore
This website and I conceive this internet site is really informative ! Keep on putting up!
ReplyDeleteData Science Course in Pune
ReplyDeleteThis is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
www.technewworld.in
How to Start A blog 2019
Eid AL ADHA
ReplyDeleteGreat post i must say and thanks for the information. Education is definitely a sticky subject. it is still among the leading topics of our time. I appreciate your post and looking for more.Data Science Courses
Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
ReplyDeleteir 4.0 training in malaysia
It’s great blog to come across a every once in a while that isn’t the same out of date rehashed material. Fantastic read.Automation Anywhere Training in Bangalore
ReplyDeleteYour article gives lots of information to me. I really appreciate your efforts admin, continue sharing more like this.
ReplyDeleteaws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore
Set your career with nearlearn’s data science training in Bangalore. This professional course will help you to understand each and all concepts of data science. Training available as online, classroom and corporate training in areas like BTM Layout, Indiranagar, Marathahalli, Koramangala, Jayanagar, and JP Nagar. We provide 100% placement assistance.
ReplyDeletedata science with Python Classroom Training in Bangalore
ReplyDeleteVery interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspried me to read more. keep it up.thanks a lot.
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
This article is very informative content. asp.net coding excellent.
ReplyDeletePython Training in Chennai
Python Training in Bangalore
Python Training in Hyderabad
Python Training in Coimbatore
Python Training
python online training
python flask training
python flask online training
.
This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information.
ReplyDeleteGreat post! Thanks for sharing this amazing post
Artificial Intelligence Training in Hyderabad
Artificial Intelligence Course in Hyderabad
This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.
ReplyDeletedata scientists training
Nice post, thanks for sharing. Also check out the link of the given website
ReplyDeleteAmbeone DMCC
Really awesome blog. Useful information and knowledgeable. Thanks for posting this blog. Keep sharing more blogs again soon.
ReplyDeleteData Science Training and Placements in Hyderabad
I can set up my new idea from this post. It gives in depth information. Thanks for this valuable information for all,..
ReplyDeletedata analytics courses in hyderabad with placements
slot siteleri
ReplyDeletekralbet
tipobet
mobil ödeme bahis
betmatik
kibris bahis siteleri
poker siteleri
bonus veren siteler
betpark
BXKN
betmatik
ReplyDeletekralbet
betpark
mobil ödeme bahis
tipobet
slot siteleri
kibris bahis siteleri
poker siteleri
bonus veren siteler
Y7M
شركة تنظيف مجالس بالدمام rsO30wb318
ReplyDelete