Home > ASP.Net, Javascript > Checkbox column with header template also having checkbox

Checkbox column with header template also having checkbox

Hi all ,

try this example to use CheckBox with header template of Gridview Control :-

Assuming that SqlDataSource1 is the datasource for my GridView

so we will add the following Javascript Code :-

<script type="text/javascript">
    function SelectAll(id) {
        var frm = document.forms[0];
        for (i=0;i<frm.elements.length;i++) {
            if (frm.elements[i].type == "checkbox") {
                frm.elements[i].checked = document.getElementById(id).checked;

and in Our Page

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
                <asp:CheckBox ID="CheckBox1" runat="server" />
                <asp:CheckBox ID="CheckBox1" runat="server" />
                <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle HorizontalAlign="Left" />

and In code behind :-

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.Header)
        //adding an attribute for onclick event on the check box in the header
        //and passing the ClientID of the Select All checkbox
        ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");

and to get checked row for delete with Delete button

foreach (GridViewRow row in GridView1.Rows)
       CheckBox checkbox = (CheckBox)row.FindControl("cbxId");
       if (checkbox.Checked == true)
           int Id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
           // your delete method here

Hope this helps

Good Luck

Categories: ASP.Net, Javascript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: