Click here to Skip to main content
Click here to Skip to main content

Display image gallery in ASP.NET GridView Control

, 3 Nov 2008
Rate this:
Please Sign up or sign in to vote.
Here we can use GridView control to display images in a gallery view with internal paging.

Introduction

In this article I will try to explain you how you can display images as a gallery view using GridView control of ASP.NET.

I face problem of paging when I had tried it with DataList control. In DataList we can define repeat column direction to display images as gallery. But main problem is paging, and you have to use third party control to apply paging in DataList and it is difficult to manage with third party control.

But here I have taken GridView control to display image gallery. With use of internal paging. So we can done all operation very simply on GridView control.

Lets Start.

1. Code for .ASPX page is as follow

                   
 <asp:GridView ID="gvListProperty" runat="server" AutoGenerateColumns="false" Width="100%"
 border="0" AllowPaging="true" BorderColor="white" cssClass="griditem" PageSize="10"  >
 <PagerSettings Mode="Numeric"  Position="TopAndBottom"/>
 <PagerStyle CssClass="mypager" HorizontalAlign="right" />
 <Columns>
     <asp:TemplateField>
   <HeaderStyle CssClass="dispnone" /> 
  <ItemTemplate>
   <table width="100%">
   <tr>
   <td class="bdr-grey">                                                    
    <table width="100%" border="0" cellspacing="0" cellpadding="0" Class="griditem" >
        <tr>
          <td width="60px" height="60px" Class="griditem" >
          <%#Container.DataItem("Column1")%>
          </td>                                                              
          <td width="60px" height="60px" Class="griditem" >
          <%#Container.DataItem("Column2")%>
          </td>                         
          <td width="60px" height="60px" Class="griditem" >
          <%#Container.DataItem("Column3")%>
          </td>                         
          <td width="60px" height="60px" Class="griditem" >
          <%#Container.DataItem("Column4")%>
          </td>
        </tr>
    </table>
   </td>
   </tr>
   </table>
  </ItemTemplate>
  </asp:TemplateField>
 </Columns>
</asp:GridView>

Here we have taken Gridview control named by “gvListProperty”. In this GridView control I have taken one template column. So in that we can apply some formatting as we want to display.

You can also apply some CSS to table inside this template column. Here we have set AllowPaging=True. Because we need to use paging in this gallery view. This GridView will display 40 records on each page. Here I have set pageSize=10 so it has fix page size to display records only 40*10=400. You can change it as per your requirement.

Paging mode is numeric and page number will display on Top and Bottom of the GridView.
First column is 4 static column noted with bold face.

Now look at <%#Container.DataItem("Column1")%>, <%#Container.DataItem("Column2")%>, <%#Container.DataItem("Column3")%>, <%#Container.DataItem("Column4")%>.

These columns I have define are not related to Database Table columns. The data will fillup in this column from code behind. Because I face problem to display images as repeat column manner. This is possible in DataList only to display record in repeat column direction. But here in GridView Control it is not possible. And same in DataList control internal paging is not possible.

2. Code behind operations.

Declaring object variable

Here you can simplify code by writing it in a region section. Declare object variable first in a code behind file. (before page load)

#Region " Data Members "
    Dim objPropertyForSale As New Propertyforsale
 #End Region

Variable objPropertyForSale is a object of class Propertyforsale.vb class file. In propertyforsale.vb you can write method to fetch data from database table.

Call function that retrive records from database

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)_
                      Handles Me.Load
 If Not IsPostBack Then

  'To set page nuber after redirecting back from detail page
   If Request.QueryString("iPn") <> Nothing Or IsNumeric(Request.QueryString("iPn")) Then

    gvListProperty.PageIndex = CInt(Request.QueryString("iPn"))

   End If

 'Call function that retrieve records from database
 Call BindPropertyGallery()
 End If
End Sub

In a page load event I am calling function that will retrieve records form table.

Here is code for this function.

Public Sub BindPropertyGallery()
    Dim dsProperty As DataSet
       With objPropertyForSale
           dsProperty = .Galleryview_PropertyList()
           If dsProperty.Tables(0).Rows.Count > 0 Then
   
              'Integrate this record with DataTable and then bind it with GridView
 
              Call DataTableBind(dsProperty)
           End If
      End With
End Sub

Galleryview_PropertyList function is written in class file propertyforSale.vb. This function will retrive records and return DataSet.

Function DataTableBind will bind this records with gridview columns.
Look below code that is written in propertyforSale.vb class file.

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports commonlib

Public Class Propertyforsale
Dim DM As New commonlib.DBManager(ConfigurationManager.ConnectionStrings(
                                                  "ConnectionString").ConnectionString)
    Dim sSql As String
    Dim retVal As New DataSet
#Region "Method"
    
Public Function Gallaryview_PropertyList() As DataSet
         sSql = "Gallaryview_PropertyList"
         retVal = DM.ExecuteDataSet(CommandType.StoredProcedure, sSql)
         Return retVal
End Function
#End Region
End Class

This is a sample code written in class file. I have created my own DBManager file, that is used for performing all DB operation. You can use DataAdepter or DataReader to do same in code behind file.

Classfile function Gallaryview_PropertyList() is returning value as DataSet. sSql is representing procedure name that used to retrive records. retVal dataset will return records back to codebehind file from where this function is called.

Now come back to code behind file operation.

Integrate this record with DataTable and then bind it with GridView

Read this code very carefully because all display and paging logic is dependent on this code. I face too much problem when writing code first time. It has taken too much time to write this simple code.

This is lengthy but very simple code.

Here I have used DataTable to insert each image in its 4 columns one by one. After 4 columns have data it will generate new row with new 4 columns and same way it rotating up to last record of the Dataset.

Public Sub DataTableBind(ByVal dsProperty As DataSet)
        '-- Paging Variables --'
        'Due to Paging Counter == 40 Records per page
        Dim iCountIncre As Integer = 40 ' Records per page
        Dim iPn As Integer = 0 'Current Page Number
        '-- End Paging Variables --' 

        Dim iCount As Integer
        Dim iColumn As Integer = 1
        Dim dtTable As New DataTable
        Dim dtCol As DataColumn
        Dim dtRow As DataRow
  
        dtCol = New DataColumn("Column1")
        dtTable.Columns.Add(dtCol)
        dtCol = New DataColumn("Column2")
        dtTable.Columns.Add(dtCol)
        dtCol = New DataColumn("Column3")
        dtTable.Columns.Add(dtCol)
        dtCol = New DataColumn("Column4")
        dtTable.Columns.Add(dtCol)
        dtRow = dtTable.NewRow
        For iCount = 0 To dsProperty.Tables(0).Rows.Count - 1
        
       'Due to Paging Counter == 40 Records per page, On Every 40 records Page number will get increment.
            If (iCount + 1) > iCountIncre Then
                iCountIncre = iCountIncre + 40
                iPn = iPn + 1
            End If
                    
       dtRow("Column" & iColumn) = "<a  href="/KB/aspnet/fulladdforrent.aspx"?iPn=" & iPn.ToString & _
                                   "&QCD=GLV&QID=" & dsProperty.Tables(0).Rows(iCount).Item("iPropertyID") & _
                                   "' class='txt-grey'> <img src='../Images/Property/thumb/" & _
                                   dsProperty.Tables(0).Rows(iCount).Item("sImageName") & _
                                   "' border='0'  alt='Vis'/>"

        'This will maintain 4 columns per row.
            iColumn = iColumn + 1
        
        'This will maintain 4 columns per row. When column get number 5, at that time it 
        'turns for new row
            If iColumn = 5 Then
                dtTable.Rows.Add(dtRow)
                dtRow = dtTable.NewRow
                iColumn = 1
            End If
          
            If iCount = dsProperty.Tables(0).Rows.Count - 1 And iColumn <= 5 Then
                dtTable.Rows.Add(dtRow)
                dtRow = dtTable.NewRow
            End If
        Next

   'Add table to the dataset
        Dim ds As New DataSet
  
        ds.Tables.Add(dtTable)
       
        'Now GridView get ds(dataset) as DataSource
        gvListProperty.DataSource = ds
        gvListProperty.DataBind()
  End Sub    

In a function DataTableBind I have passed a dataset with records. Here I have taken variable dtTable of type DataTable. As explain early. dtTable has 4 columns DataColumn("Column1") to DataColumn("Column4"). If you can’t getting why I have taken this then again look at column description of GridView control explain early on.

For Loop with iCount will run up to last record of the dataset.

Variable iCountIncre will get increment of value 40 at every 40 records so we can manage page number consistency. This is why because we have to pass current page number of browsed image gallery page to its detail page. And when returning back from detail page to gallery view at that time we have to maintain this page number.

Variable iColumn is used to maintain column consistency from column no.1 to 4. Because here we have to display 4 images at each row.

dtRow("Column" & iColumn) = "<a href="/KB/aspnet/fulladdforrent.aspx"?iPn=" & iPn.ToString & "&QID=" &_
                            dsProperty.Tables(0).Rows(iCount).Item("iPropertyID") &_
                            "' class='txt-grey'> <img src='../Images/Property/thumb/" &_
                            dsProperty.Tables(0).Rows(iCount).Item("sImageName") &_
                            "' border='0' alt='View'/>" 

In this logic dtRow(“Column” & iColumn) will be like this dtRow(“Column1”) and upto dtRow(“Column4”).

So this dtRow has Column and that column value will display image in gallery because it call that image from path with image name from database table dsProperty.Tables(0).Rows(iCount).Item("sImageName").

And link on that image represent the link page name with iPn (page number), iPropertyID (because image is related to that property. It represent unique id of property).

ds.Tables.Add(dtTable) 

And after that bind this table with dataset “ds”. And bind this dataset “ds” to GridView.

Following code is used to manage paging of GridView control.

Protected Sub gvListProperty_PageIndexChanging(ByVal sender As Object, _
                          ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) & _ 
 Handles gvListProperty.PageIndexChanging 
  gvListProperty.PageIndex = e.NewPageIndex 
  Call BindPropertyGallary() 
End Sub 

When user click on any page number it will call this event and code written inside this event will change the current page index and assign new page number to GridView and bind this GridView again with record. After binding GridView the page which you see it is of new assign page number.

 

One more thing I want to share with you that is I also got suggestion to bind this GridView in RowDataBound Event of the GridView. To bind this GridView in RowDataBound we have to take Record Dataset either Public Variable or in a ViewState and then need to do some extra operation then as I wrote in function DataTableBind(). So Dataset with records in Public Variable or with ViewState will occupy more memory compare to existing code memory usage. That's why I had let go that concept.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vimal Panara
Technical Lead IndiaNIC Infotech Ltd
India India
No Biography provided

Comments and Discussions

 
Questionbrilliant PinmemberdnpAA6-Jun-12 22:55 
QuestionI could't load commonlid, help me PinmemberMember 435196930-Oct-11 20:50 
QuestionHow to display images retrieved from database in GridView using web user control PinmemberMember 330449015-Jul-11 1:22 
Generalhi,,,,Thank you for tis code...it helped me a lot Pinmembershishir.sasal20-May-11 19:08 
GeneralMasterPageFile="~/MasterPage.master" PinmemberMember 78937323-May-11 11:30 
QuestionIs there C# version??? Pinmembersimpa14-Mar-11 8:12 
QuestionThanks for the code Pinmembermukulsh8-Apr-10 23:58 
AnswerRe: Thanks for the code [modified] PinmemberVimal Panara30-Jul-10 20:21 
Generaltable VS CSS Pinmemberigorgordon@gmail.com10-Nov-08 11:11 
GeneralGreat admiration PinmemberMember 26295094-Nov-08 20:10 
GeneralGood one! Pinmembermahesh@indianic.com4-Nov-08 17:34 
AnswerRe: Good one! PinmemberMember 26295094-Nov-08 19:57 
Thanks Mahesh,
 
I would like to say about your suggestion for RowDataBound. To bind this GridView in RowDataBound we have to take Record Dataset either Public Variable or in a ViewState and then need to same operation as I wrote in function DataTableBind(). So Dataset with records in Public Variable or with ViewState will occupy more memory compare to existing code memory usage. That's why I had let go that concept.
 
Thanks for your hawk eye.
 
Smile | :)
 
him

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 4 Nov 2008
Article Copyright 2008 by Vimal Panara
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid