Unchecking and Checking all items in a GridView

Part of the code were derive from this Forum
Clicking button to include (Button2) or exlude all (Button1) items in the gridview (GridView1),
checking (Button2) or unchecking (Button1) all items in the gridview (GridView1), FieldName is name of the field that you wish to store the value. checkbox1 is the name of the checkbox inside the gridview control.

    protected void Button1_Click(object sender, EventArgs e)
    {
        for (int iCount = 0; iCount < GridView1.Rows.Count; iCount++)
        {
            if (GridView1.Rows[iCount].RowType == DataControlRowType.DataRow)
            {
                CheckBox cb = (CheckBox)GridView1.Rows[iCount].Cells[0].FindControl(“checkbox1“);
                cb.Checked = false;

            Use  hidden = GridView1.Row.Cells[0].FindControl(“FieldName“) as HiddenField; oor this one below
        hidden = (HiddenField)GridView1.Rows[iCount].Cells[0].FindControl(“FieldName“);
                hidden.Value = “0”;
            }
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
       for(int iCount=0 ; iCount < GridView1.Rows.Count ; iCount++)
       {
           if (GridView1.Rows[iCount].RowType == DataControlRowType.DataRow)
           {
               CheckBox cb = (CheckBox)GridView1.Rows[iCount].Cells[0].FindControl(“checkbox1“);
               cb.Checked = true;
              
            Use hidden = GridView1.Row.Cells[0].FindControl(“FieldName“) as HiddenField; or this one below
           hidden = (HiddenField)GridView1.Rows[iCount].Cells[0].FindControl(“FieldName“);
               hidden.Value = “1”;
           }
       }
    }

Upon loading the form, all rows are checked as default.
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            hidden = new HiddenField();
            hidden = e.Row.Cells[0].FindControl(“FieldName“) as HiddenField;

            chkbox = e.Row.Cells[0].FindControl(“checkbox1“) as CheckBox;
            if (Convert.ToInt32(hidden.Value) > 0)
            {
                chkbox.Checked = true;
            }
            else if (hidden.Value == “0”)
            {
                chkbox.Checked = false;
            }
        }
    }

Advertisements
This entry was posted in ASP.NET 2. Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

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