Thursday, 15 November 2012

Checkbox in Gridview Using Javascript


Checkbox in Gridview Using Javascript


We sometime wants some checkboxes to be associated with the gridview so that the user can select specific or all the items inside the gridview and we could perform our task based upon the selected items..
Here is a way to do this:

Design Part:


<asp:GridView ID="gdvShowData" runat="server" AutoGenerateColumns="False" CssClass="gdvBody" Width="100%" >

<Columns>

   <asp:TemplateField>

       <HeaderTemplate>

               <asp:CheckBox ID="chkheader" runat="server"  onclick="Calculate(this);" ToolTip="Check to select all rows"/>

       </HeaderTemplate>

       <ItemTemplate>

               <asp:CheckBox ID="chkchild" runat="server" />

       </ItemTemplate>

   <ItemStyle Width="8%" />

</asp:TemplateField>        

    <asp:BoundField HeaderText="Name" DataField="Name" />            

 </Columns>

 <EmptyDataTemplate>

    There is no record.

 </EmptyDataTemplate>

</asp:GridView>



function Calculate(SelectAllCheckBox)

{

        var chkAll=document.getElementById(SelectAllCheckBox.id);

        var Parentgrid = document.getElementById('<%= gdvShowData.ClientID %>');      

        var items = Parentgrid.getElementsByTagName('input');

        for (i = 1; i < items.length; i++)

        {        

            if (items[i].type == "checkbox")

            {              

                if (chkAll)

                 items[i].checked = chkAll.checked;              

            }

        }

}

function Selectchildcheckboxes(header)

{

    var ck = header;

    var count = 0;

    var gvcheck = document.getElementById('gdvShowData');

    var headerchk = document.getElementById(header);

    var rowcount = gvcheck.rows.length;

    for (i = 1; i < gvcheck.rows.length; i++)

   {

       var inputs = gvcheck.rows[i].getElementsByTagName('input');

       if (inputs[0].checked)

      {

            count++;

       }

    }

     if (count == rowcount-1)

    {

           headerchk.checked = true;

     }

    else

    {

           headerchk.checked = false;

     }

}


Code Behind:


protected void gdvShowData_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

CheckBox headerchk = (CheckBox)gdvShowData.HeaderRow.FindControl("chkheader");

CheckBox childchk = (CheckBox)e.Row.FindControl("chkchild");

childchk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + headerchk.ClientID + "')");

}

}


No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top