Monday, November 17, 2014

Gridview Checkbox event handling


Note:  The code below will help to understand gridview checkbox field event handling operations like check-uncheck single row and check-uncheck all (header row).

1.       For adding checkbox field in gridview (gridUsser) we are using template field as follows :

<asp:TemplateField>

       <HeaderTemplate>

<asp:CheckBox ID="chkHeader" runat="server" OnCheckedChanged="chkHeader_CheckedChanged" AutoPostBack="true" />

       </HeaderTemplate>

       <ItemTemplate>

<asp:CheckBox ID="chkData" runat="server" OnCheckedChanged="chkData_CheckedChanged" AutoPostBack="true" />

       </ItemTemplate>

</asp:TemplateField>

2.        For individual rows checked – unchecked events following code is used

 

    protected void chkData_CheckedChanged(object sender, EventArgs e)

    {

        //check/uncheck specific

        CheckBox chb = (CheckBox)sender;

        if (chb.Checked == true)

       {

//code here

       }

        else

        {

           //code here

        }

    }

 

 

3.       For All row checked – unchecked operation following code is used

 

protected void chkHeader_CheckedChanged(object sender, EventArgs e)

    {

        //check/uncheck all

 

        CheckBox chbAll = (CheckBox)sender;

        if (chbAll.Checked == true)

        {

            for (int i = 0; i < gridUsser.Rows.Count; i++)

            {

                try

                {

                    CheckBox cb = (CheckBox)gridUsser.Rows[i].Cells[0].Controls[1];

                    cb.Checked = true;
                  
                    //Code here;

                }

                catch (Exception)

                {
  
                    //throw;

                }

            }

           

        }

        else

        {

            for (int i = 0; i < gridUsser.Rows.Count; i++)

            {

                try

                {

                    CheckBox cb = (CheckBox)gridUsser.Rows[i].Cells[0].Controls[1];

                    cb.Checked = false;
                   
                    //throw;

                }

                catch (Exception)

                {
                    //throw;

                }

            }

        }    

    }

 

No comments:

Post a Comment