Displaying images from the server’s folder is pretty simple. All you need is a path to the image in the database and you simply assign the path to the ASP.NET image control. Unfortunately, sometimes saving the images in the folder becomes cumbersome due to the requirements of the application. In this article I will explain how you can store the images in the database and later display the images into a GridView control.



Introduction:


Displaying images from the server’s folder is pretty simple. All you need is a path to the image in the database and you simply assign the path to the ASP.NET image control. Unfortunately, sometimes saving the images in the folder becomes cumbersome due to the requirements of the application. In this article I will explain how you can store the images in the database and later display the images into a GridView control.

Database Design:

I used SQL SERVER 2005 Express Edition to create the database. The database contains two tables namely animal_Animals and animal_AnimalTypes. As, you have guessed I will be storing animal images into the database. In case you are wondering what kind of animals then it is cats and dogs.

Inserting Image into the Database:

The first task is to insert the animal image and related information into the database. For this purpose I have developed a small form which allows the user to select an image from his machine and upload it to the database.

 

The form above is very simple which gather the basic information about the image and uses the ASP.NET 2.0 FileUpload control to select the file from the user’s machine. If you are using .NET 1.X then you can also use FileField control which is contained in the HTML Tab of the toolbox.

You can check out the AddAnimal_Click code listed below:

protected void AddAnimal_Click(object sender, EventArgs e)
    {      
        Animal animal = new Animal();
        animal.Name = txtName.Text;
        animal.AnimalType.AnimalTypeID = Convert.ToInt32(ddlAnimalTypes.SelectedValue);
        // Now get the image

        Stream s =  fu.PostedFile.InputStream;
        // length in bytes
       
        int length = fu.PostedFile.ContentLength;
        animal.Picture = new byte[length];

        s.Read(animal.Picture, 0, length);      

        s.Close();
        animal.Save();                 
       
    }


The AddAnimal_Click event is generated when the user clicks the “Add” button to insert a new animal into the database. I have created an Animal class with properties like “Name”, “AnimalType” and “Picture” which defines the behavior of an animal. Since, the database field AnimalImage is of type “Image” we had to use a byte array to hold the animal’s picture.

The “Save” method is where the actual database call is made and the data is inserted.

public void Save()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["PhotoAlbumConnectionString"].ConnectionString;
        string insertQuery = "INSERT INTO animal_Animals(Name, AnimalTypeID, AnimalImage) VALUES(@Name,@AnimalTypeID, @AnimalImage)";

        using (SqlConnection myConnection = new SqlConnection(connectionString))
        {
            SqlCommand myCommand = new SqlCommand(insertQuery, myConnection);
            myCommand.Parameters.AddWithValue("@Name", this.name);
            myCommand.Parameters.AddWithValue("AnimalTypeID", this.AnimalType.AnimalTypeID);
            myCommand.Parameters.AddWithValue("@AnimalImage", this.Picture);

            myConnection.Open();
            myCommand.ExecuteNonQuery();
        }  

    }


Nothing special about the Save method, it simply uses an insert query to insert a new record in the database.

Displaying Image in the GridView Control:

In the previous section I described how you can insert an image in the database, in this section I will demonstrate how you can display an image from the database in the GridView control.

Let’s first set up our GridView control. Check out the HTML code for the GridView control.

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />           
           
            <Columns>
           
            <asp:TemplateField HeaderText="Name">
           
            <ItemTemplate>
            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
            </ItemTemplate>                     
           
            </asp:TemplateField>
           
           <asp:ImageField DataImageUrlField="AnimalID" DataImageUrlFormatString="ViewImage.aspx?animalID={0}" />
                   
           
            </Columns>
           
        </asp:GridView>


The only important thing to notice about the above code is the line  <asp:ImageField DataImageUrlField="AnimalID" DataImageUrlFormatString="ViewImage.aspx?animalID={0}" /> which is used to display the image. DataImageUrlField represents the ID which is passed to the page defined by the DataImageUrlFormatString attribute.

Now, let’s take a look at the ViewImage.aspx page which serves as a gofer and gets the images.

private void BindData()
    {              
        Animal animal = new Animal();
        int animalID = 0;

        if(Request.QueryString["animalID"] != null)
            animalID = Convert.ToInt32( Request.QueryString["animalID"]);



        byte[] animalImage = animal.GetImageByID(animalID);

        Response.OutputStream.Write(animalImage, 0, animalImage.Length);
    }

The BindData method gets the animalID from the query string and gets the image from the database using the GetImageByID method. Finally, the image is written to the output stream using the Response.OutputStream.Write method.




Conclusion:

In this article we learned how to insert images into the database and display them in the GridView control. In future article I will discuss how you can resize the image and then display a thumbnail rather then displaying the original size.

I hope you liked the article, happy programming!

PLS: Aren’t the cats too cute?