CheckBox Column In GridView handled using Client-Site Script (Javascript)

GridViewImage

Purpose:

handled the check box check event without postback using javascript and save the id in the hidden field. in the above

“fig1” user selected the check one by one. after the selection of all the check box the header is selected which is described

in the “fig2”. now user is changed the page index described in the “fig3” and selected the page1 described in the “fig4” here all

the check box is checked.

Steps:

1) Create the Simple Web Application.

2)put the below code in the .aspx file.

<asp:HiddenField  ID="TotalNoOfRecord" Value="," runat="server"/>
    <asp:HiddenField ID="SelectedRecord" Value ="," runat ="server" />
    <div>
        <asp:GridView AutoGenerateColumns="False" ID="GridView1" 
        runat="server" Style="z-index: 100; left: 326px; position: absolute;
            top: 148px" OnRowDataBound="GridView1_RowDataBound" 
            AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" 
            PageSize="5" CellPadding="4" ForeColor="#333333" GridLines="None">
            <Columns>
            <asp:TemplateField>
            <HeaderTemplate>
            <asp:CheckBox ID="chkHeader" runat="server" />
            </HeaderTemplate>
            <ItemTemplate>
            <asp:CheckBox ID="chkItemTemplate" runat="server" />
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Id" Visible="False">
            <ItemTemplate>
            <asp:Label ID="lblId" Text='<%# Eval("Id") %>' runat="server"></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText ="Code">
            <ItemTemplate>
            <asp:Label ID="lblCode" Text='<%# Eval("Code") %>' runat="server"></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    
    </div>

3) put the below Javascript in to code.

 <script language="Javascript" type="text/javascript">
    //fire when the header checkbox is click
    function SelectAll(chkid)
    {
    //get the form
     var objfrm = document.forms[0];
     //find the element length of the form
     for (i=0;i<objfrm.elements.length;i++)
     {
       //check the element type (it is check box) and it in the gridview1 
       if (objfrm.elements[i].type == "checkbox" && objfrm.elements[i].name.indexOf('<%= GridView1.ClientID %>') >= 0)
       {
           objfrm.elements[i].checked = document.getElementById(chkid).checked;
       }
     }
      //get the hidden field of the selected id
      var SelectedRecord = document.getElementById('SelectedRecord').value;
      //selectedid in the hidden field
      var hdnIds = SelectedRecord.split(",");
      //no of record on the page
      var hdnnoofrecord = document.getElementById('TotalNoOfRecord').value.split(",");
        
     if(document.getElementById(chkid).checked)
     {    
        //check the value in the SelectedRecord
        for(var i=1;i< hdnnoofrecord.length-1;i++)
        {    
            //if already exist at that time we not added that id into the 
            //SelectedRecord else Add
            if(SelectedRecord.indexOf(',' + hdnnoofrecord[i] +',')<0)
            {
                SelectedRecord += hdnnoofrecord[i] + ',';
            }
        }       
        document.getElementById('SelectedRecord').value =SelectedRecord;
     }
     else
     {
      //check the value in the SelectedRecord
        for(var i=1;i< hdnnoofrecord.length-1;i++)
        {
          //unselected row id is replace (example id 1 is unchecked --> ,1, replace with ,)  
          SelectedRecord = SelectedRecord.replace(',' + hdnnoofrecord[i] + ',',','); ;
        }        
         document.getElementById('SelectedRecord').value =SelectedRecord;
     }
     
    }
    
    //header checkbox check /uncheck function
    function HeaderCheckUnCheck()
    {
        var header =true;
        var chkheaderchkbox;
        var AllRecordSelect = true;
        var objfrm = document.forms[0];
         
        for (i=0;i<objfrm.elements.length;i++)
        {
          if (objfrm.elements[i].type == "checkbox" && objfrm.elements[i].name.indexOf('<%= GridView1.ClientID %>') >= 0)
          {
           if(header ==true)
           {
            chkheaderchkbox=objfrm.elements[i];
            header =false;
           } 
           else
           {
            if(objfrm.elements[i].checked ==false) 
            {
             AllRecordSelect =false;
            }
           }
          }
        }
        //all the row check box is checked then header check box is click
         if(AllRecordSelect ==true)
         {
             chkheaderchkbox.checked =true;
         }
         else 
         {
            chkheaderchkbox.checked =false;
         }
    }
    //individual check box click at that time fire
    function Select(chkid,selectedrowvalue)
    {    
        var SelectedIds =document.getElementById('SelectedRecord').value;
        if(document.getElementById(chkid).checked)
        {
            if(SelectedIds.indexOf(',' + selectedrowvalue + ',') <0)
                SelectedIds += selectedrowvalue + ',';
        }
        else
        {
            SelectedIds = SelectedIds.replace(',' + selectedrowvalue + ',',',');
        }   
        document.getElementById('SelectedRecord').value = SelectedIds;
        HeaderCheckUnCheck();
    }
    </script>

4) Here I Created one class instead of connection with database. here class is serialized because i save the data in the viewstate.

[Serializable]
public class MyData
{
  private int _Id;
 
  public int Id
  {
    get { return _Id; }
    set { _Id = value; }
  }
 
  private String _Code;
 
  public String Code
  {
    get { return _Code; }
    set { _Code = value; }
  }
 
  public MyData(int id, string code)
  {
    this.Id = id;
    this.Code = code;
  }
}

5) put the below code in the .CS File.

 public System.Collections.Generic.List<MyData> Data
  {
    get { if (ViewState["data"] ==null)
            return new System.Collections.Generic.List<MyData>( );
      return (System.Collections.Generic.List<MyData> ) ViewState["data"]; }
    set { ViewState["data"] = value; }
  }
    
 
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        System.Collections.Generic.List<MyData> obj = new System.Collections.Generic.List<MyData>();
         
        for (int i = 0; i < 10; i++)
        {
          obj.Add(new MyData(i,"a" + i.ToString()  ));
        }
 
        Data = obj;
        GridView1.DataSource = Data;
        GridView1.DataBind();
 
      }
 
      Response.Write(SelectedRecord.Value);
      //Response.Write(TotalNoOfRecord.Value);
    }
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.Header)
    {
      CheckBox chk = ((CheckBox)e.Row.FindControl("chkHeader"));
      chk.Attributes.Add("onclick", "SelectAll('" + chk.ClientID + "');");
    }
    else if(e.Row.RowType ==DataControlRowType.DataRow)
    {
      CheckBox chk = ((CheckBox)e.Row.FindControl("chkItemTemplate"));
      Label lbl = ((Label)e.Row.FindControl("lblId"));
      chk.Attributes.Add("onclick","Select('" + chk.ClientID + "' ,'" + lbl.Text + "')");
 
      if (SelectedRecord.Value.Contains("," + lbl.Text + ","))
      {
        chk.Checked = true;
      }
 
      TotalNoOfRecord.Value += lbl.Text +",";
    }
   
  }
  protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
  {
    TotalNoOfRecord.Value = ",";
    GridView1.PageIndex = e.NewPageIndex;
    GridView1.DataSource = Data;
    GridView1.DataBind();
  }
Thnx 
Advertisements

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