Selecting Checkboxes inside the GridView Control


Introduction

 

The ASP.NET GridView control is the successor to the ASP.NET DataGrid control which has many built in functionalities like paging, sorting, editing or deleting data. In this article I will explain how to select checkboxes inside the GridView control.

 

Scenario

 

Let us take a real time scenario to develop a user interface which should list the users and to assign permissions like select, add, edit and all to the users. For the select attribute only select permissions is enabled, add attribute has select and add permissions, edit attribute has select, add and edit permissions and finally the all attribute has select, add, edit and delete permissions.

 

Solution

 

Let us build the user interface for the above mentioned scenario. To achieve this let us place a GridView control in the web page. To the GridView control add four template fields to place the check boxes inside the GridView control and a bound field for displaying the user id.

 

GridView.JPG

The GridView definition will be like this

 

            <asp:GridView ID="GridView1" runat="server"  AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" CellPadding="4" ForeColor="#333333" GridLines="None">

                <Columns>

                    <asp:BoundField DataField="UserId" HeaderText="User Id" />

                    <asp:TemplateField HeaderText="Select">

                        <ItemTemplate>

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

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Add">

                        <ItemTemplate>

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

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="Edit">

                        <ItemTemplate>

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

                        </ItemTemplate>

                    </asp:TemplateField>

                    <asp:TemplateField HeaderText="All">

                        <ItemTemplate>

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

                        </ItemTemplate>

                    </asp:TemplateField>

                </Columns>

                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

                <EditRowStyle BackColor="#999999" />

                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

            </asp:GridView>

 

In the code behind let us populate the GridView with some data from a XML file.

 

    private void CreateDataSource()

    {

        //Create a data table users

        DataTable dataTable = new DataTable("Users");

 

        //Create a column UserId to store the user id

        DataColumn userId = new DataColumn("UserId", Type.GetType("System.String"));

       

        //Create a column Select to store the select permission access

        DataColumn select = new DataColumn("Select", Type.GetType("System.Boolean"));

       

        //Create a column Add to store the add permission access

        DataColumn add = new DataColumn("Add", Type.GetType("System.Boolean"));

 

        //Create a column Edit to store the edit permission access

        DataColumn edit = new DataColumn("Edit", Type.GetType("System.Boolean"));

 

        //Create a column All to store the all permission access

        DataColumn all = new DataColumn("All", Type.GetType("System.Boolean"));

 

        //Add the columns to the table

        dataTable.Columns.Add(userId);

        dataTable.Columns.Add(select);

        dataTable.Columns.Add(add);

        dataTable.Columns.Add(edit);

        dataTable.Columns.Add(all);

 

        //Load the data from xml file into the data table

        dataTable.ReadXml(Server.MapPath("~/App_Data/data.xml"));

 

        //Bind the grid view with the data source

        GridView1.DataSource = dataTable;

        GridView1.DataBind();

    }

 

The GridView RowDataBound Event

 

The RowDataBound event occurs when a data row is bound to data in a GridView control. Before the GridView control can be rendered, each row in the control must be bound to a record in the data source. The RowDataBound event is raised when a data row is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs. In this we are going to find the check boxes in the GridView control and create a new attribute for the checkboxes. The new attribute will be an onclick event which will invoke a JavaScript function when a user clicks the checkboxes.

 

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        //Check for the row type, which should be data row

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

        {

            //Find the check boxes and assign the values from the data source

            ((CheckBox)e.Row.FindControl("chkSelect")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[1]);

            ((CheckBox)e.Row.FindControl("chkAdd")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[2]);

            ((CheckBox)e.Row.FindControl("chkEdit")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[3]);

            ((CheckBox)e.Row.FindControl("chkAll")).Checked = Convert.ToBoolean(((DataRowView)e.Row.DataItem)[4]);

 

            //Find the checkboxes and assign the javascript function which should

            //be called when the user clicks the checkboxes.

 

            ((CheckBox)e.Row.FindControl("chkSelect")).Attributes.Add("onclick", "checkBoxClicked('" +

((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID

+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'SELECT')");

 

            ((CheckBox)e.Row.FindControl("chkAdd")).Attributes.Add("onclick", "checkBoxClicked('" +

((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID

+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'ADD')");

 

            ((CheckBox)e.Row.FindControl("chkEdit")).Attributes.Add("onclick", "checkBoxClicked('" +

((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID

+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'EDIT')");

 

            ((CheckBox)e.Row.FindControl("chkAll")).Attributes.Add("onclick", "checkBoxClicked('" +

((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAdd")).ClientID

+ "','" + ((CheckBox)e.Row.FindControl("chkEdit")).ClientID + "','" + ((CheckBox)e.Row.FindControl("chkAll")).ClientID + "'," + "'ALL')");

 

        }

    }

 

The Client Side Code

 

We have done with our code behind code and let us create the JavaScript functions which will do the required job for us to complete this task. The below JavaScript functions will allow the users to select the checkboxes as per our business rule "For the select attribute only select permissions is enabled, add attribute has select and add permissions, edit attribute has select, add and edit permissions and finally the all attribute has select, add, edit and delete permissions".

 

    //Function checkBoxClicked checks the checkboxes based on the user input

      function checkBoxClicked(cbxSelect,cbxAdd,cbxEdit,cbxAll,ctl)

      {

            var cbkSelect = document.getElementById(cbxSelect);

            var cbkAdd = document.getElementById(cbxAdd);

            var cbkEdit = document.getElementById(cbxEdit);

            var cbkAll = document.getElementById(cbxAll);

 

            var itemChecked = getCheckedItem(cbxSelect,cbxAdd,cbxEdit,cbxAll,ctl);

           

            if(itemChecked == "false")

            {

                  if(ctl == "SELECT")

                  {

                        if(cbkSelect.checked == true)

                        {

                              cbkSelect.checked = true;

                              cbkAdd.checked = false;

                              cbkEdit.checked = false;

                              cbkAll.checked = false;

                        }

                        else

                        {

                              cbkSelect.checked = false;

                              cbkAdd.checked = false;

                              cbkEdit.checked = false;

                              cbkAll.checked = false;

                        }

                  }

                  else if(ctl == "ADD")

                  {

                        if(cbkAdd.checked == true)

                        {

                              cbkSelect.checked = true;

                              cbkAdd.checked = true;

                              cbkEdit.checked = false;

                              cbkAll.checked = false;

                        }

                        else

                        {

                              cbkSelect.checked = false;

                              cbkAdd.checked = false;

                              cbkEdit.checked = false;

                              cbkAll.checked = false;

                        }

                  }

                  else if(ctl == "EDIT")

                  {

                        if(cbkEdit.checked == true)

                        {

                              cbkSelect.checked = true;

                              cbkAdd.checked = true;

                              cbkEdit.checked = true;

                              cbkAll.checked = false;

                        }

                        else

                        {

                              cbkSelect.checked = false;

                              cbkAdd.checked = false;

                              cbkEdit.checked = false;

                              cbkAll.checked = false;

                        }

                  }

                  else if(ctl == "ALL")

                  {

                        if(cbkAll.checked == true)

                        {

                              cbkSelect.checked = true;

                              cbkAdd.checked = true;

                              cbkEdit.checked = true;

                              cbkAll.checked = true;

                        }

                        else

                        {

                              cbkSelect.checked = false;

                              cbkAdd.checked = false;

                              cbkEdit.checked = false;

                              cbkAll.checked = false;

                        }

                  }

            }

            else

            {

                  if(ctl == "SELECT")

                  {

                        cbkSelect.checked = true;

                  }

                  else if(ctl == "ADD")

                  {

                        cbkAdd.checked = true;

                  }

                  else if(ctl == "EDIT")

                  {

                        cbkEdit.checked = true;

                  }

                  else if(ctl == "ALL")

                  {

                        cbkAll.checked = true;

                  }

            }

      }

 

    //Function getCheckedItem returns the previously selected checkboxes.

      function getCheckedItem(cbxSelect,cbxAdd,cbxEdit,cbxAll,ctl)

      {

            var cbxSelect = document.getElementById(cbxSelect);

            var cbkAdd = document.getElementById(cbxAdd);

            var cbkEdit = document.getElementById(cbxEdit);

            var cbkAll = document.getElementById(cbxAll);

           

            var retVal = "false";

                       

            if(ctl == "SELECT")

            {

                  if(cbkAdd.checked == true || cbkEdit.checked == true || cbkAll.checked == true)

                  {

                        retVal = "true";

                  }

                  else

                  {

                        retVal = "false";

                  }

            }

            else if(ctl == "ADD")

            {

                  if(cbkEdit.checked == true || cbkAll.checked == true)

                  {

                        retVal = "true";

                  }

                  else

                  {

                        retVal = "false";

                  }

            }

            else if(ctl == "EDIT")

            {

                  if(cbkAll.checked == true)

                  {

                        retVal = "true";

                  }

                  else

                  {

                        retVal = "false";

                  }

            }

            else if(ctl == "ALL")

            {

                  retVal = "false";

            }          

            return retVal;

 

      }

 

Conclusion

 

In this article we have seen how to select checkboxes inside a GridView control. The scenario which we had discussed can be done easily using the server side code but at the cost of page postback. This client side approach provides the user a smooth experience but requires some JavaScript coding to achieve this functionality.

Up Next
    Ebook Download
    View all
    Learn
    View all