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

Handling GridView events using RowCommand and using jQuery

, 14 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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

<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>

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.

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

<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: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)

Share

About the Author

vinodkumarnie
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.
Follow on   Google+

Comments and Discussions

 
GeneralMy vote of 4 PinmemberJepy9-Apr-13 0:50 
Simple to understand and to use.
GeneralRe: My vote of 4 Pinmembervinodkumarnie9-Apr-13 6:42 
QuestionNot an article PinmemberKarthik Harve3-Apr-13 18:01 
AnswerRe: Not an article Pinmembervinodkumarnie3-Apr-13 18:36 
GeneralRe: Not an article PinmemberKarthik Harve3-Apr-13 18:56 
GeneralRe: Not an article Pinmembervinodkumarnie3-Apr-13 19:19 
GeneralMy vote of 5 PinmemberNandakishorerao3-Apr-13 17:54 
GeneralRe: My vote of 5 Pinmembervinodkumarnie12-Apr-13 20:02 

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
Web04 | 2.8.141022.2 | Last Updated 14 Apr 2013
Article Copyright 2013 by vinodkumarnie
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid