Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET

Show Hide Grid Content using Server side(.Net) and Client side(JQuery)

Rate me:
Please Sign up or sign in to vote.
4.87/5 (15 votes)
18 Jul 2017CPOL3 min read 61.6K   915   29   10
Handling controls inside GridView using RowCommand and jQuery.
Don't forget to give your votes ! 

Introduction

GridView is powerful control in ASP.NET where we can have other controls inside it and also we can have GridView inside GridView. This article tells about how to access controls and events inside GridView.

Also this article includes

  1. Inserting rows into GridView through code behind using data table
  2. RowCommand event functionality and its usages
  3. Handling contols through ClientSide and also through code behind
  4. Importance of jQuery and its usages
  5. Handling controls using jQuery
  6. jQuery functions like parent(), next(), show(), hide() controls functionalists.

Background

In many situations nested controls are very much necessary. So GridView is the best control to do the same. Also some people not even know how to handle controls which are inside GridView. Also jQuery got very much famous now a days in handling controls in Client Side. That is what I thought to write an Article about the same which can understood easily by everyone.

Using the code 

The GridView view mode displays a list of data items by binding data fields to columns and by displaying a column header to identify the field. The default GridView style implements buttons as column headers. By using buttons for column headers, you can implement important user interaction capabilities; for example, users can click the column header to sort GridView data according to the contents of a specific column.

GridView columns are represented by GridViewColumn objects, which can automatically size to their content. Optionally, you can explicitly set a GridViewColumn to a specific width. You can resize columns by dragging the gripper between column headers. You can also dynamically add, remove, replace, and reorder columns because this functionality is built into GridView. However, GridView cannot directly update the data that it displays.

GridView Events are click here

Now I will explain how to access controls and event using RowCommand and jQuery

1. Using RowCommand 

The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs. Mean to say on click of button inside GridView you can perform custom operation. CommandName is used to give unique name to identify the event. CommandArgument passes the Row index value to Command Event..

Example:

In below example using I am adding rows into GridView using DataTable on PageLoad event.  

GridView_CodeBehind.aspx.cs

C#
protected void Page_Load(object sender, EventArgs e)//page load event
{
    if (!this.IsPostBack)
    {
        load_gridviewrecords();// calling function to add rows into GridView 
    }
}
private void load_gridviewrecords() // adding 3 rows
{
    DataTable dt = new DataTable();
    dt.Columns.Add("jobid");
    dt.Columns.Add("jobtitle");
    dt.Columns.Add("positions");
    dt.Columns.Add("Description");
    DataRow dr1 = dt.NewRow();
    dr1["jobid"] = "JOB122";
    dr1["jobtitle"] = "Software Engineer";
    dr1["positions"] = "10";
    dr1["Description"] = "This job not direct. You have to apply through online. " + 
      "Qualification required BE (Computer Science), M.Tech(Computer Science), " + 
      "MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr1);
    DataRow dr2 = dt.NewRow();
    dr2["jobid"] = "JOB123";
    dr2["jobtitle"] = "Associate System Engineer";
    dr2["positions"] = "100";
    dr2["Description"] = "This job not direct. You have to apply through online. " + 
      "Basic knowledge of web development. Qualification required BE (Computer Science), " + 
      "M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr2);
    DataRow dr3 = dt.NewRow();
    dr3["jobid"] = "JOB124";
    dr3["jobtitle"] = "Web designer";
    dr3["positions"] = "5";
    dr3["Description"] = "This job not direct. You have to apply through online. " + 
      "Required skills css, Jquery, Html, Photoshop. Qualification required BE " + 
      "(Computer Science), M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr3);
    dt.AcceptChanges();
    GridView1.DataSource = dt;
    GridView1.DataBind();
    
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)// on imagebutton click
{
    if (e.CommandName == "showhide")
    {
        int index = int.Parse(e.CommandArgument.ToString());
        GridViewRow gr = GridView1.Rows[index];
        ImageButton imgbtn = (ImageButton)gr.FindControl("ImageButton1");
        Panel pnl = (Panel)gr.FindControl("pnlOrders");
        if (pnl.Visible == false)
        {
            imgbtn.ImageUrl = "minus.jpg";
            pnl.Visible = true;
        }
        else
        {
            imgbtn.ImageUrl = "plus.jpg";
            pnl.Visible = false;
        }
    }
}

GridView_CodeBehind.aspx

XML
<style type="text/css">
        body{font-family:Calibri;}
    .jobid{float:left; width:100px; height:auto;}
    .jobtitle{float:left; width:300px; height:auto;}
    .noofpositions{float:left; width:100px; height:auto;}
    .div_parent{float:left; width:100%; height:auto;}
    .panel_description{float:left; width:100%; height:auto;}
    </style>

<asp:GridView ID="GridView1" runat="server" 
            ShowHeader="false" ShowFooter="false"
            AutoGenerateColumns="false" GridLines="None" Border="1" 
            onrowcommand="GridView1_RowCommand" >
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <div style="width:500px; height:auto;">
                    <div class="jobid">
                        <asp:Label ID="Label1" runat="server" 
                              Text='<%# Eval("jobid") %>'></asp:Label>
                    </div>
                    <div class="jobtitle">
                        <asp:Label ID="Label2" runat="server" 
                              Text='<%# Eval("jobtitle") %>'></asp:Label>
                    </div>
                    <div class="noofpositions">
                        <asp:Label ID="Label3" runat="server" 
                           Text='<%# Eval("positions") %>'></asp:Label>
                    </div>
                    <div style="clear:both; height:auto; border-top:solid 1px #e2e2e2;"></div>
                        <div class="div_parent">
                            <asp:ImageButton ID="ImageButton1" CommandName="showhide" 
                              CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" 
                              style="cursor: pointer" ImageUrl="plus.jpg" 
                              width="40" height="40" 
                              title="Description" runat="server" />
                        </div>
                        <asp:Panel ID="pnlOrders" class="panel_description" 
                                  runat="server" Visible="false">
                            <asp:Label ID="lblMsg" runat="server" 
                              Text='<%# Eval("description") %>'></asp:Label>
                        </asp:Panel>
               </div>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Image 1

Initially I am making panel containing description ant set visibility to false. OnClick of Image button making the panel visibility to true based on RowIndex also changing the ImageButton Image to minus.jpg.

Image 2

2. Achieving the same using jQuery 

GridView_JQuery.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        load_gridviewrecords();
    }
}
private void load_gridviewrecords()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("jobid");
    dt.Columns.Add("jobtitle");
    dt.Columns.Add("positions");
    dt.Columns.Add("Description");
    DataRow dr1 = dt.NewRow();
    dr1["jobid"] = "JOB122";
    dr1["jobtitle"] = "Software Engineer";
    dr1["positions"] = "10";
    dr1["Description"] = "This job not direct. You have to apply through online. " + 
      "Qualification required BE (Computer Science), " + 
      "M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr1);
    DataRow dr2 = dt.NewRow();
    dr2["jobid"] = "JOB123";
    dr2["jobtitle"] = "Associate System Engineer";
    dr2["positions"] = "100";
    dr2["Description"] = "This job not direct. You have to apply through online. " + 
      "Basic knowledge of web development. Qualification required BE (Computer Science), " + 
      "M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr2);
    DataRow dr3 = dt.NewRow();
    dr3["jobid"] = "JOB124";
    dr3["jobtitle"] = "Web designer";
    dr3["positions"] = "5";
    dr3["Description"] = "This job not direct. You have to apply through " + 
      "online. Required skills css, Jquery, Html, Photoshop. Qualification required BE " + 
      "(Computer Science), M.Tech(Computer Science), MCA. Year of passout 2011, 2012.";
    dt.Rows.Add(dr3);
    dt.AcceptChanges();
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

GridView_JQuery.aspx

HTML
<style type="text/css">
        body{font-family:Calibri;}
    .jobid{float:left; width:100px; height:auto;}
    .jobtitle{float:left; width:300px; height:auto;}
    .noofpositions{float:left; width:100px; height:auto;}
    .div_parent{float:left; width:100%; height:auto;}
    .panel_description{float:left; width:100%; height:auto;}
    </style>
 
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
    $('.div_parent img').each(function()
    {
        var flag_click=0;
        $(this).click(function()
        {
            if(flag_click===0)
            {
                $(this).attr("src","minus.jpg");
                $(this).parent(".div_parent").next(".panel_description").show();
                flag_click++;
            }
            else
            {
                $(this).attr("src","plus.jpg");
                $(this).parent(".div_parent").next(".panel_description").hide();
                flag_click=0;
            }
        });
    });
});
</script>
ASP.NET
<asp:GridView ID="GridView1" runat="server" 
            ShowHeader="false" ShowFooter="false"
            AutoGenerateColumns="false" GridLines="None" Border="1">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <div style="width:500px; height:auto;">
                    <div class="jobid">
                        <asp:Label ID="Label1" runat="server" 
                          Text='<%# Eval("jobid") %>'></asp:Label>
                    </div>
                    <div class="jobtitle">
                        <asp:Label ID="Label2" runat="server" 
                          Text='<%# Eval("jobtitle") %>'></asp:Label>
                    </div>
                    <div class="noofpositions">
                        <asp:Label ID="Label3" runat="server" 
                           Text='<%# Eval("positions") %>'></asp:Label>
                    </div>
                    <div style="clear:both; height:auto; border-top:solid 1px #e2e2e2;"></div>
                        <div class="div_parent">
                        <img alt="" style="cursor: pointer"
                           src="plus.jpg" width="40" height="40" 
                           title="Description" /></div>
                        <asp:Panel ID="pnlOrders" class="panel_description" 
                                    runat="server" Style="display:none;">
                            <asp:Label ID="lblMsg" runat="server" 
                               Text='<%# Eval("description") %>'></asp:Label>
                        </asp:Panel>
                   </div>
                        
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In the above example, the jQuery function parent() is used to find the parent control and next() is used to find immediate controls. After finding control, using show() and hide() functions we can make panel control show and hide, respectively.

Points of Interest 

We done show/hide controls using both the ways using RowCommnad and using jQuery. The interesting thing you need to know is that jQuery will reset to its original state after PostBack event occurs. Mean to say in above example if postback occurs all description panels will be set to hidden state. So Handling PostBack event is differ from code behind to jQuery.  

License

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


Written By
Software Developer Sonata Software Pvt Ltd
India India
Hi.. I am Vinod Kumar B C from Mysore, Karnataka. I have done MCA and currently working as a Software Engineer having 3 Years of Experience in web development. I know Asp.net, C#, MVC, Sql Server, CSS, JQuery, C, C++, HTML, DB2, DataStructures.

Comments and Discussions

 
QuestionGreat! Well done. I learned from this! Pin
Member 1086218019-Jul-17 9:11
Member 1086218019-Jul-17 9:11 
AnswerRe: Great! Well done. I learned from this! Pin
vinodkumarnie13-Aug-17 20:38
vinodkumarnie13-Aug-17 20:38 
QuestionI guess article title is wrong Pin
Mou_kol19-Jun-17 23:17
Mou_kol19-Jun-17 23:17 
GeneralMy vote of 4 Pin
Jepy9-Apr-13 0:50
Jepy9-Apr-13 0:50 
GeneralRe: My vote of 4 Pin
vinodkumarnie9-Apr-13 6:42
vinodkumarnie9-Apr-13 6:42 
QuestionNot an article Pin
Karthik Harve3-Apr-13 18:01
professionalKarthik Harve3-Apr-13 18:01 
AnswerRe: Not an article Pin
vinodkumarnie3-Apr-13 18:36
vinodkumarnie3-Apr-13 18:36 
GeneralRe: Not an article Pin
Karthik Harve3-Apr-13 18:56
professionalKarthik Harve3-Apr-13 18:56 
GeneralRe: Not an article Pin
vinodkumarnie3-Apr-13 19:19
vinodkumarnie3-Apr-13 19:19 
GeneralMy vote of 5 Pin
Nandakishore G N3-Apr-13 17:54
professionalNandakishore G N3-Apr-13 17:54 
GeneralRe: My vote of 5 Pin
vinodkumarnie12-Apr-13 20:02
vinodkumarnie12-Apr-13 20:02 

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.