Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET
Tip/Trick

Expandable Table like Gridview

Rate me:
Please Sign up or sign in to vote.
4.89/5 (9 votes)
26 Mar 2014CPOL2 min read 18.3K   266   7   7
Virtual Expandable Gridview using Ajax post method

Image 1

Introduction

In this tip, I am going to write about Expandable table using Ajax post method. I have used Div having name "tblUsers" to append using jQuery Ajax post method.

Let's see further in detail about that.

Background

In this tip, all the users data has been structured in gridview form.

Using Ajax post method, all user's data is retrieved and set to Div using jQuery.

It is very fast and smooth during expansion and there is no need for any other third party DLLs or setups.

Using the Code

I have implemented code here. There is only one page for making an expandable table. It is very easy and fast.

First, create a database named DemoDatabase in your SQL Server and that runs that script in your SQL server (only for this demo purpose, you can integrate your own database in this demo):

SQL
  CREATE TABLE [dbo].[Users](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
    [UserName] [varchar](50) NULL,
    [Email] [nvarchar](150) NULL,
    [imageURL] [nvarchar](max) NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Users] ON 

GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (1, N'Nirav', N'Prabtani', N'Nills', _
N'niravjprabtani@gmail.com', N'nirav.jpg')
GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (2, N'Rajan', N'Mrug', N'Raj', _
N'Raj@gmail.com', N'rajan.jpg')
GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (3, N'Rajesh', N'Saradhara', N'Rajesh', _
N'rajesh@yahoo.in', N'rajesh.jpg')
GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (4, N'Dharmendra', N'Pansara', _
N'Dhamo', N'Dhamo@hotmail.com', N'demo.jpg')
GO
SET IDENTITY_INSERT [dbo].[Users] OFF
GO 

Now create WebForm IndexTable in your project.

1) IndexTable.aspx

Javascript Code

JavaScript
  <script src="js/jquery%20-1.8.3.min.js" 
type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {
        //Call BindUsers function during Page load
            BindUsers();

        });

        //Bind all data to div using ajax Post method
        function BindUsers() {

            $.ajax({
                type: 'POST', // Method type
                url: 'IndexTable.aspx/GetUsers', //Page URL/Function Name 
                data: {}, //Parameters
                contentType: 'application/json',
                dataType: 'json',
                success: function (data) { //Returned data

                    if (data.d.length > 0) { //Check Count of data

                        // Set Div to empty.
                        $("#tblUsers").empty(); 

                      //Create Header of a Tbale
                        $("#tblUsers").append("<tr class='trHead'  
                        ><td class='tdHead'>Firstname</td>
                        <td class='tdHead'>Lastname</td>
                        <td class='tdHead'>Username</td></tr>");

                        //Bind Div in tabular form using For loop

                        for (var i = 0; i < data.d.length; i++) {
                            $("#tblUsers").append("<tr   
                            onclick='ExpandGrid(" + data.d[i].id + ")' >
                            <td class='tdHead'>" + data.d[i].FirstName + "
                            </td><td class='tdHead'>" + data.d[i].LastName + "
                            </td><td class='tdHead'>" + data.d[i].UserName + "
                            </td></tr><tr style='display:none;background-color:#F2F2F2' 
                            id='trExpand" + data.d[i].id + "'><td valign='middle' 
                            align='center' ><img src='Images/" + data.d[i].ImageURL + 
                            "' height='80px' width='50px'></td>
                            <td colspan='2' align='center' valign='middle'>
                            <table><tr><td><input id='txtFirstName" + 
                            data.d[i].id + "' value=" + data.d[i].FirstName + " >
                            </td></tr><td><input id='txtLastName" + 
                            data.d[i].id + "' value=" + data.d[i].LastName + " >
                            </td><tr><td><input id='txtUserName" + data.d[i].id + 
                            "' value=" + data.d[i].UserName + " ></td></tr>
                            <tr><td><input id='txtEmail" + data.d[i].id + "' 
                            value=" + data.d[i].Email + " ></td></tr></table>  
                            </td> </tr>");
                        }
                    }
                },
                error: function (result) { //Call on failure or error

                    alert(result.d);
                }
            });
        }

        //Function for expansion of a table
        function ExpandGrid(id) {

            $("#trExpand" + id).toggle(300);
        }

    </script> 

CSS Styles

CSS
<style>
     .trHead
     {
         height: 30px;
         background-color: #c8c8c8;
         color: White;
         font-weight: bold;
     }
     .tdHead
     {
         width: 150px;
         border: 1px solid #c8c8c8;
         height: 30px;
         vertical-align: middle;
         padding-left: 5px;
         cursor: pointer;
     }
     .trExpand
     {
         border: 1px solid #c8c8c8;
     }
 </style>

HTML Code

HTML
<div>
  <%--Div Which has been Binded--%>
      <div id="tblUsers">
      </div>
 </div>

2) IndexTable.aspx.cs

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

namespace ExpandableTable
{
    public partial class IndexTable : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        // Get All users data

        [WebMethod]
        public static Users[] GetUsers()
        {
            // Create Object of a list
            List<Users> Details = new List<Users>();


            //Select All users data from SQL database
            string SelectUsers = "select * from Users";
            SqlConnection cn = new SqlConnection
            (ConfigurationManager.ConnectionStrings["cs_Users"].ConnectionString);
            SqlCommand cmd = new SqlCommand(SelectUsers, cn);

            cn.Open();
            cmd.ExecuteNonQuery();

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtUsers = new DataTable();

            da.Fill(dtUsers);

            //Insert all users data into LIST
            foreach (DataRow dtrow in dtUsers.Rows)
            {
                Users Dataobj = new Users();
                Dataobj.id = Convert.ToInt32(dtrow["id"]);
                Dataobj.FirstName = dtrow["FirstName"].ToString();
                Dataobj.LastName = dtrow["LastName"].ToString();
                Dataobj.UserName = dtrow["UserName"].ToString();
                Dataobj.Email = dtrow["Email"].ToString();
                Dataobj.ImageURL = dtrow["imageURL"].ToString();
                Details.Add(Dataobj);
            }

            //Return array value to bind data
            return Details.ToArray();
        }

        //Class of users
        public class Users
        {
            public int id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string UserName { get; set; }
            public string Email { get; set; }
            public string ImageURL { get; set; }
        }
    }
} 

In this manner Div "tblUsers" has been bound using Ajax Post method like Expandable table.

How Does It Work??

When application is started, first of all, jQuery page load method occurs and using Ajax post method WebMethod GetUsers() is called and all users data from database returned in array format using Users class.

We can struct Div using append jQuery syntax.

In this example, there are two <tr> tags that have been initialized in Div, one is visible and the second is invisible using CSS property "display:block".

When Div will bind, it will look like that:

Image 2

There are four Users, therefore there are four columns in a table.

Now if you click on any column of a table, then the second row which is already invisible is set to visible by calling JavaScript function ExpandGrid():

JavaScript
function ExpandGrid(id) {
            $("#trExpand" + id).toggle(300);
        } 

and it will look like...

Image 3

Points of Interest

I have designed it in a very simple form. You can modify by simply assigning styles or classes.

We can also put up and down arrows for expanding functionality.

We can apply transition effects using jQuery during expansion of table.

History

  • 27th March 2014: Initial post

License

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


Written By
Team Leader eInfochips
India India



Nirav Prabtani




I am a team lead, Database Architect and Designer /Technical Architect/Analyst,
Programmer in Microsoft .NET Technologies & Microsoft SQL Server with more than
4.5 years of hands on experience.



I love to code....!!! Smile | :)



My recent past includes my work with the education domain as a technical business
requirement analyst, database architect & designer and analyst programmer; just
love my involvement with the world of knowledge, learning and education and I think
I know quite well what I want to do in life & in my career. What do I like? Well,
ideation, brainstorming, coming up with newer and more creative ways of doing things;
each time with an enhanced efficiency. An item in my day's agenda always has a task
to look at what I did yesterday & focus on how I can do it better today




Contact Me

Nirav Prabtani


Mobile : +91 738 308 2188



Email : niravjprabtani@gmail.com


My Blog:
Nirav Prabtani



Comments and Discussions

 
QuestionA nice initial effort Pin
ahagel27-Mar-14 7:40
professionalahagel27-Mar-14 7:40 
QuestionThanks, I will give to it a 4.5 out 5 Pin
bigwelly7627-Mar-14 2:36
bigwelly7627-Mar-14 2:36 
AnswerRe: Thanks, I will give to it a 4.5 out 5 Pin
Nirav Prabtani27-Mar-14 2:42
professionalNirav Prabtani27-Mar-14 2:42 
GeneralMy vote of 4 Pin
Pratik Bhuva26-Mar-14 21:25
professionalPratik Bhuva26-Mar-14 21:25 
GeneralRe: My vote of 4 Pin
Nirav Prabtani26-Mar-14 22:46
professionalNirav Prabtani26-Mar-14 22:46 
GeneralThanks... Pin
HardikPatel.SE26-Mar-14 18:49
professionalHardikPatel.SE26-Mar-14 18:49 
GeneralRe: Thanks... Pin
Nirav Prabtani26-Mar-14 18:51
professionalNirav Prabtani26-Mar-14 18:51 

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

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