This
tutorial will show you how to store images to database and bind to gridView. I
have used FileUpload control to upload image from our computer and it’ll be
stored to database as binary format and display these images to GridView.
First we have to create a table with
three fields, ImageID, ImageName and Image. We need to store Image as binary
format so we have to use varbinary() datatype.

Store Image:
Once we created our table then we have
to design our ASPX page. First we have add TextBox control for image name,
FileUpload control for image and Button to initiate upload.
<div>
<asp:TextBox ID="txtImageName"
runat="server">
</asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click"
/>
</div>
Connection string:
Here
we have to add connection string to the web.config file
<connectionStrings>
<add name="myConnectionString" connectionString="Data
Source=localhost; Initial Catalog=Demo; User Id=sa;Password=sa123"/>
</connectionStrings>
On button click event we have to write
following code to store image to database. Here we are going to convert image
to binary format and it’ll be stored along with Image name. You will see that BinaryReader receives filestream to
convert Image as binary data and it’ll be stored to byte array.
protected void btnSubmit_Click(object sender, EventArgs
e)
{
try
{
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new
BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(
"INSERT INTO tblImage (ImageName,
Image) " +
"Values(@ImageName, @Image)",
connection);
command.Parameters.Add("@ImageName",
SqlDbType.NVarChar, 20).Value = txtImageName.Text;
command.Parameters.Add("@Image",
SqlDbType.Binary).Value = bytes;
connection.Open();
command.ExecuteNonQuery();
}
}
catch (Exception)
{ //error }
}
Retrieve Image:
We have Image that has been stored to
database as binary format. Now we are going to retrieve Image from database and
we will display that to GridView. For that we have to add GridView Control to
our .aspx page. In GridView we have to add BoundField for Image Name and
TemplateField for Image. Then we have to create a Handler that will return
Image from query string.
GridView
control look like this
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ImageName"
HeaderText="Image
Name"/>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="imgPreview"
ImageUrl='<%#
"ImageHandler.ashx?imgID="+
Eval("ImageID") %>' runat="server"
Height="80px"
Width="80px"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Bind GridView C# code:
protected void bindGrid()
{
DataSet ds = new DataSet();
using (SqlConnection
connection = new SqlConnection(connectionString))
{
connection.Open();
string cmdstr = "Select
ImageId, ImageName from tblImage";
SqlCommand cmd = new
SqlCommand(cmdstr, connection);
SqlDataAdapter adp = new
SqlDataAdapter(cmd);
adp.Fill(ds);
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
}
Create Handler:
Right click root folder -> Add New
Item and add Generic Handler(ashx).

Now we have Handler file containing "ProcessRequest(HttpContext
context)" method which gets triggered automatically.
public void ProcessRequest(HttpContext
context)
{
SqlDataReader rdr = null;
SqlConnection conn = null;
SqlCommand selcmd = null;
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
selcmd = new SqlCommand("select Image from tblImage where ImageID=" + context.Request.QueryString["imgID"], conn);
conn.Open();
rdr = selcmd.ExecuteReader();
while (rdr.Read())
{
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite((byte[])rdr["Image"]);
}
rdr.Close();
}
finally
{
conn.Close();
}
}
I
hope you understand how to store images to database and bind to GridView. You
can download source code which is available along with this article.
Happy
coding.. J