Simple Photo Gallery in ASP.NET

Raj.Trivedi
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 14728 red flag

Hello Team,

In this article we will see how we can create a simple Photo Gallery in asp.net using Data List Control in asp.net

Introduction


Hello Team,

Its one of the most searched items and required feature in todays application development world i.e. Creating a Photo Gallery App.

In this article we will see how we can achieve the same.

Its the very basic creation that we are looking for and i hope this will especially help for beginners.



Objective


  1. Uploading Image in Folder and storing the path in the database.
  2. Binding the Image to a Data List Control and design it in such a way where it will look like a Gallery.
  3. Viewing the Image in Full Size.
  4. Paging the Data List so that we can browse we can navigate if the images are more.



Using the code


  1. Open Visual Studio -> Create a New Empty Web site.
  2. Add 2 Web form as AddImage.aspx and PhotoGallery.aspx
  3. Now right Click on the Name of the Website in the Solution Explorer and add a  Folder and name it as Images.
  4. In this folder we will upload the Image from the AddImage.aspx
  5. In the PhotoGallery.aspx we will show the images in rows and columns having 3 rows and 4 Columns.


Explanation of AddImage.aspx

  1. Drag and Drop a File Upload Control,Textbox and a Button on the webpage.
  2. The File Upload control will allow us to browse the Computer for Images.
  3. The Textbox will allow us to input the name of the Image.
  4. The Button will upload the Image in the Images Folder that we have created in the Application and also insert the path in the database to display the images in datalist.

Explanation of PhotoGallery.aspx

  1. In this page we will drag and drop a Datalist and in the html mark up we will set its Repeat Direction property to Horizontal and repeat columns as 3.
  2. Since we have taken a Datalist we have to mandatory use Item Template so that we can use the Image control and show it on our Page.
  3. Item Template is actually the place where the all the Items are hold in the datalist.
  4. Now drag and drop an Image Control and a Hyperlink in Item Template and set its height and width to 300.
  5. Now Add and Item style to make the Datalist look good.In this we will set the border to datalist with white color and 20px so that we can have nice spacing between Images.
  6. Now we will drag and drop 4 buttons name it as First, Previous, Next,Last...This will help us to navigate to pages if we have more images, this can be termed as Paging as we have it in Grid View.
  7. Remember there is no Inbuilt Paging Functionality in datalist.
  8. Now in the code behind in PageLoad event we have executed a Function called Binddatalist.
  9. This function will get images from the database and show it in the datalist.
  10. Now to show the images in the datalist we will be using the Eval bind method in the HTML mark up.
  11. The Eval method will take the Database Column to bind the image.
  12. This Eval mehod has to be assigned to ImageUrl.
  13. This is the Code <asp:Image ID="ximages" ImageUrl='<%#Eval("Images") %>' Width="200" Height="200" runat="server">
  14. The above code is also there in the Code section.
  15. The Hyperlink will allow us to see the Image in Full size.
  16. When we click on the Hyperlink it will take to that image in the browser.

Paging in Datalist

  1. To do a Paging in DataList we will use a PagedDatasource Class that will allow us to do cutom paging.
  2. First we will create an object of Paged Datasource and in the Binddatalist function we will set the allow paging property to true.
  3. We will set the pagesize to 12,
  4. Then we will check the current page index and store to a Int variable.
  5. Now we will get the images in the dataset and then we will assign that dataset to object of the paged datasource and then we will assign the PagedDatasource to the datalist datasource.
Navigation in Paging

  1. We will declare a Global variable named Pagenumber and its datatype to int.
  2. In this we will store the Pagenumber.
  3. On the page Load event we will set the pagenumber to 0 and hold it into viewstate property.
  4. Since we have taken 4 Button First,Last,Previous,Next
  5. On the Click of the First button we will set the page number to 0; but the First button will only work when the user is not on the First Page and if he is already on the First Page then the button is disabled.
  6. For Last page first we check the total number of pagecount and then we decrement by 1 as the PageCount starts from 0;and if the user is already on the last page the button will be disabled.
  7. Now for previous and Next button we will check the page number that is stored in the View State and for previous button we will decrements the page by 1 and for next we will go to + 1 and store it in the view state.
  8. If you are on the First Page then The previous button is disabled and if you are on the Last Page then the next button is disabled. 
  9. Explanation for the lines of code is also there in the code.


// Database Tables and Stored Procs
-- Table for storing images

CREATE TABLE [dbo].[ImageGallery](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ImageName] [varchar](50) NULL,
	[Images] [varchar](max) NULL
) ON [PRIMARY]

GO


-- Stored Procedure for Inserting Images
create proc [dbo].[InsertImages]
(
@ImageName varchar(50),
@Images varchar(max)
)
as
begin
insert into ImageGallery(ImageName,Images)
values
(@ImageName,@Images)
end

-- Stored Proc for Getting images from database
create proc [dbo].[GetImages]
as
begin 
select * from ImageGallery
end
// HTML Mark up and Code behind Code for AddImage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddImage.aspx.cs" Inherits="AddImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 134px;
        }
        .style3
        {
            width: 217px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table class="style1">
            <tr>
                <td class="style2">
                    Browse Image</td>
                <td class="style3">
                    <asp:FileUpload ID="fupdf" runat="server" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2">
                    Image Name</td>
                <td class="style3">
                    <asp:TextBox ID="xtxtImageName" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    <asp:Button ID="btnUpload" runat="server" Text="Upload and Save" 
                        onclick="btnUpload_Click" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
    
    </div>

    </form>
</body>
</html>


---- Code Behind.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Configuration;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.WebControls;

public partial class AddImage : System.Web.UI.Page
{
   
    string errdesc = "0";
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            // Connection String
            string strconn = ConfigurationManager.ConnectionStrings["cnnLocal"].ConnectionString;
            SqlConnection con = new SqlConnection(strconn);

            // Getting the extension for the images

            string extension = Path.GetExtension(fupdf.FileName);

            // Getting the File name of Images

            string filename = Path.GetFileName(fupdf.FileName);

            // This will get the actual path for upload.

            string uploadFolder = Request.PhysicalApplicationPath + "Images\\";

            // This path will go in database because asp.net requires virtual path.

            string upload = "~/Images/" + filename;

            // Saving the images in the folder

            fupdf.SaveAs(uploadFolder + filename);

            string getfile = upload;

            SqlCommand cmdins = new SqlCommand("InsertImages", con);
            cmdins.CommandType = CommandType.StoredProcedure;
            cmdins.Parameters.AddWithValue("@ImageName", SqlDbType.VarChar).Value = xtxtImageName.Text;
            cmdins.Parameters.AddWithValue("@Images", getfile);
            con.Open();
            cmdins.ExecuteNonQuery();
            Literal1.Text = "Data Saved";
            con.Close();
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
            Literal1.Text = errdesc;
        }
        
    }
}		
//HTML Mark up and Code behind for PhotoGallery.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PhotoGallery.aspx.cs" Inherits="PhotoGallery" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 62%;
            margin-left: 0px;
        }
        .style2
        {
            width: 56px;
        }
        .style3
        {
            width: 71px;
        }
        .style4
        {
            width: 162px;
        }
        .style5
        {
            font-family: "Courier New";
            font-size: xx-large;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
        <h1 class="style5">
            Basic
    Photo Gallery : Using Data List</h1>
        <br />
        <br />
&nbsp;<asp:DataList ID="DataList1" RepeatDirection="Horizontal" RepeatColumns="4" runat="server">
        <ItemTemplate>
        <asp:Image ID="ximages" ImageUrl='<%#Eval("Images") %>' Width="200" Height="200" runat="server">
            
            </asp:Image>
            <br />
            <asp:HyperLink ID="lnkview" NavigateUrl='<%#Eval("Images") %>' runat="server">View Full Size</asp:HyperLink>
        </ItemTemplate>
        <ItemStyle BorderColor="White" BorderStyle="Solid" BorderWidth="20px" HorizontalAlign="Center"
VerticalAlign="Bottom" />
            
        </asp:DataList>
        
    </div>
   
    <p>
        &nbsp;</p>
        <div align="center">
    <table class="style1">
        <tr>
            <td class="style2">
                <asp:Button ID="btnFirst" runat="server" Text="First" onclick="btnFirst_Click" 
                    Width="217px" BackColor="#000099" Font-Bold="True" Font-Italic="False" 
                    Font-Size="Medium" ForeColor="White" />
            </td>
            <td class="style3">
                <asp:Button ID="btnPrevious" runat="server" Text="Previous" 
                    onclick="btnPrevious_Click" Width="240px" BackColor="#003399" 
                    Font-Bold="True" Font-Size="Medium" ForeColor="White" />
            </td>
            <td class="style4">
                <asp:Button ID="btnNext" runat="server" Text="Next" onclick="btnNext_Click" 
                    Width="218px" BackColor="#000099" Font-Bold="True" Font-Size="Medium" 
                    ForeColor="White" />
            </td>
            <td>
                <asp:Button ID="btnLast" runat="server" Text="Last" onclick="btnLast_Click" 
                    style="margin-left: 0px" Width="236px" BackColor="#000099" 
                    Font-Bold="True" Font-Size="Medium" ForeColor="White" />
            </td>
        </tr>
    </table>
    </div>
   
    </form>
</body>
</html>


// Code behind.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class PhotoGallery : System.Web.UI.Page
{
     string strconn = ConfigurationManager.ConnectionStrings["cnnLocal"].ConnectionString;
     string desc = "0";

    // creating the object of the paged data source class

     PagedDataSource objds = new PagedDataSource();
     int pagenumber;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Storing the pagenumber to 0 if the page is loading for the first time.

            this.ViewState["StoringPageNumber"] = 0;
            pagenumber = (int)this.ViewState["StoringPageNumber"];
        }
        BindDatalist();
    }


    private void BindDatalist()
    {
        try
        {

            // setting the paging to true.

            objds.AllowPaging = true;

            // deciding the page size and setting it... we are setting to 12 items on one page in datalist

            objds.PageSize = 12;

            // Checking the Current Page Index

            objds.CurrentPageIndex = pagenumber;

            // Enabling the First Button if the page is not on the first page. 

            btnFirst.Enabled = !objds.IsFirstPage;

            // Enabling the Previous Button if the page is not on the first page.

            btnPrevious.Enabled = !objds.IsFirstPage;

            // Enabling the Last Button if the page is not on the Last page.

            btnNext.Enabled = !objds.IsLastPage;

            // Enabling the Last Button if the page is not on the Last page.

            btnLast.Enabled = !objds.IsLastPage;

            SqlConnection con = new SqlConnection(strconn);
            con.Open();
            SqlCommand cmdins = new SqlCommand();
            cmdins.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand("GetImages", con);
            DataSet ds = new DataSet();

            // getting the images from database to dataset

            da.Fill(ds, "images");

            // Assigning the dataset as a DataSource to object of PagedDataSource

            objds.DataSource = ds.Tables[0].DefaultView;

            // Assigning the object of PagedDataSource to the datasource of Datalist

            DataList1.DataSource = objds;
            DataList1.DataBind();
        }

        catch (Exception ex)
        {
            
        }
    }


    protected void btnFirst_Click(object sender, EventArgs e)
    {
        // setting the pagenumber to 0 on click of first button and navigating to the first page.

        pagenumber = 0;
        BindDatalist();
    }


    protected void btnPrevious_Click(object sender, EventArgs e)
    {
        // Checking the page Number and decrementing by 1  and navigating to the page.
        pagenumber = (int)this.ViewState["StoringPageNumber"];
        pagenumber -= 1;
        this.ViewState["StoringPageNumber"] = pagenumber;
        BindDatalist();
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        // Checking the page Number and incrementing by 1  and navigating to the page.

        pagenumber = (int)this.ViewState["StoringPageNumber"];
        pagenumber += 1;
        this.ViewState["StoringPageNumber"] = pagenumber;
        BindDatalist();
    }
    protected void btnLast_Click(object sender, EventArgs e)
    {
        pagenumber = objds.PageCount - 1;
        BindDatalist();
    }
}						


Screens


AddImage.aspx




Photo Gallery.aspx




ViewFullSize



Note :- View Full Size is not a page in the project it just navigates to the image that we have clicked...We have assigned
EVAL("Images") to  Navigate URL property and hence we can go to the Image in fullsize.


Conclusion

Hope this will be good for beginers !!!!



Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)