Store Image into Database and Retrieve in a Gridview Display using C#

Database Structure

db_image

Fileupload.aspx

  1. <asp:FileUpload ID=”FileUpload” runat=”server” />  
  2.   
  3. <asp:Button ID=”btnsubmit” runat=”server” Text=”Upload” OnClick=”btnsubmit_Click” />  
  4.   
  5. <asp:Label ID=”alert” runat=”server”></asp:Label>  
  6.   
  7. <asp:gridview ID=”Fileup” runat=”server” />  

Fileupload.aspx.cs

Storing a image into database:

CODE:

  1. protected void btnsubmit_Click(object sender, EventArgs e)  
  2. {  
  3.    try  
  4.    {  
  5.       byte[] imgbyte = null;  
  6.       if(FileUpload.HasFile & FileUpload.PostedFile != null)  
  7.       {  
  8.          HttpPostedFile file = FileUpload.PostedFile;  
  9.          imgbyte = new byte[file.ContentLength];  
  10.          file.InputStream.Read(imgbyte, 0, file.ContentLength);  
  11.       }  
  12.       SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[“userconnstring”].ConnectionString);  
  13.       SqlCommand cmd = new SqlCommand(“insert into tbl_Imgdb ([Image_Name],[Image_Detail]) values (@Image_Name,@Image_Detail)”, con);  
  14.       con.Open();  
  15.       cmd.Parameters.AddWithValue(“@Image_Name”, FileUpload.PostedFile.FileName);  
  16.       cmd.Parameters.AddWithValue(“@Image_Detail”, imgbyte);  
  17.       cmd.ExecuteNonQuery();  
  18.       alert.Text = “Image Uploaded Successfully”;  
  19.       con.Close();  
  20.    }  
  21.    catch(Exception ex)  
  22.    {  
  23.       throw ex;  
  24.    }  
  25. }  

 

Binding a image ina gridview display

Configure_datasource

Add this code in a gridview column (to convert the image. display into gridview)

  1. <asp:TemplateField>  
  2.    <HeaderTemplate>Image_Detail</HeaderTemplate>  
  3.    <ItemTemplate>  
  4.    <img src=’data:Image_Detail/jpg;base64,   <%# Eval(“Image_Detail”) != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval(“Image_Detail”)) : string.Empty %>’ alt=”image” height=”75px” width=”100px”/>  
  5.    </ItemTemplate>  
  6. </asp:TemplateField>  

Output:

Screen 1:

Fileupload

Screen 2:[Uploading Image]

image_grid

Ebook Download
View all
Learn
View all