Background
After my article Uploading Images to Database Using ASP.NET C# I have often been asked how to upload images to a database and displaying them from the database using ASP.Net C#. So to satisfy those the requirements I decided to write this article especially focusing on beginners and those who want to learn how to upload images to a database and display those images.
Now before creating the application, let us create a table named "ImageToDB" or whatever name you wish in a database to store the uploaded image files in a database table having the following fields (shown in the following image),
Then after that don't forget to set the identity specification of the id column to yes, because in this application Id is an important role for retrieving the images, if you don't know how to set it then see the following example.
When you select the id column of the above table then it shows the column properties as,
Now in the image above, you see the "Is Identity" property, set it to "yes".
In the preceding table, the ImageName column name is used to store the name of an image file and the image is used to store the image file .
I hope you have created the same type of table.
Now let us start to create an application to upload and display image files step-by-step.
Now create the project as,
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
- Give the project a name, such as "DisplayingImages" or another as you wish and specify the location.
- Then right-click on Solution Explorer - "Add New Item" - "Default.aspx" page.
- One File upload control, one Button, one TextBox, one label and one Image control to display images.
Then the <form> section of the Default.aspx page looks as in the following,
- <form id="form1" runat="server">
- <tr> Name
- <td>
- <asp:TextBox ID="TextBox1" runat="server" /> </td>
- <td>
- <td> Select Image </td>
- <td>
- <asp:FileUpload ID="FileUpload1" runat="server" /> </td>
- </td>
- </tr>
- </table>
- <table>
- <tr>
- <td>
- <p>
- <asp:Label ID="Label2" runat="server" Text="label"></asp:Label>
- </p>
- </td>
- </tr>
- </table>
- </div>
- </form>
Now we need to add a Handler file to our project to display images from the database because we are saving images in binary format to get the binary formatted data we are using the Handler class. To know more about the handler class please refer to the MSDN forum.
Adding Handler Class
1. Right-click on your project add a new Handler1.ashx file as,
In the preceding image, we can see the .ashx extension file, now keep the name as it is or change it as you wish, I have kept it as it is because the next time you can easily remember it and click on the add button, now after that your Solution Explorer will look as in the following,
Now switch to design mode to code behind and create the following method to upload the image files as,
- private void Imageupload()
- {
- if (FileUpload1.HasFile)
- {
- int imagefilelenth = FileUpload1.PostedFile.ContentLength;
- byte[] imgarray = new byte[imagefilelenth];
- HttpPostedFile image = FileUpload1.PostedFile;
- image.InputStream.Read(imgarray, 0, imagefilelenth);
- connection();
- query = "Insert into ImageToDB (ImageName, Image) values (@Name, @Image)";
- SqlCommand com = new SqlCommand(query, con);
- com.Parameters.AddWithValue("@Name", SqlDbType.VarChar).Value = TextBox1.Text;
- com.Parameters.AddWithValue("@Image", SqlDbType.Image) Value = imgarray;
- com.ExecuteNonQuery();
- Label1.Visible = true;
- Label1.Text = "Image Is Uploaded successfully";
- imagebindGrid();
- }
- }
Now double-click on the "Imageupload" button and call the preceding method on it as,
- protected void upload(object sender, EventArgs e)
- {
- Imageupload();
- }
Now, create the method to bind to the GridView as,
- public void imagebindGrid()
- {
- connection();
- query = "Select id, ImageName, Image from ImageToDB";
- SqlCommand com = new SqlCommand(query, con);
- SqlDataReader dr = com.ExecuteReader();
- Gridview1.DataSource = dr;
- Gridview1.DataBind();
- }
And call preceding "Imagebindgirdmethod"() on page load as,
- protected void Page_Load(object sender, EventArgs e)
- {
- Label1.Visible = false;
- if (!IsPostBack)
- imagebindGrid();
- }
Now, open the "Handler1.ashx.cs" and write the following code,
- public class Handler1 : IHttpHandler
- {
-
-
- Default cls = new Default();
- public void ProcessRequest(HttpContext context)
- {
-
- string displayimgid = context.Request.QueryString["id_Image"].ToString();
- cls.connection();
-
-
- cls.query = "select Image from ImageToDB where id=" + displayimgid;
- SqlCommand com = new SqlCommand(cls.query, cls.con);
- SqlDataReader dr = com.ExecuteReade();
- dr.Read();
- context.Response.BinaryWrite((Byte[])dr[0]);
- context.Response.End();
- }
- }
In the preceding Handler1.ashx.cs file, first I have created the object of the default.aspx.cs class to use the connection method and variable to avoid the repetition of code because in the handler.ashx.cs file we also need the same connection method and string variables that are in the default.aspx.cs class.
Now, the most important thing is to specify the image URL property of the image control that display the images from the database, so let us see how to do it.
ImageUrl='<%# "Handler1.ashx?id_Image="+ Eval("id") %>'
Now run, the application that will look like as in the following,
Now upload the images that will display the output as follows,
In preceding output, you can clearly see that my uploaded image is displayed in the GridView with file name and image.
Note
- For detailed code please download the zip file attached above.
- Don't forget to update the "Web.config" file for your server location.
Summary
Now we have learned how to upload images to a database and display those images in GridView. I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.