GridView CheckBox Select All using JavaScript and VB.Net

Updated on 04 Sep 2012,
Published on 27 Jul 2010

Select all ASP.Net GridView Checkbox controls with single click functionality can also be accomplished by using Javascript client side scripting. In the previous tutorial about GridView Checkbox select all using VB.Net we learned the server side coding to select all the checkboxes in a single click. Here we will discuss the use of Javascript client end script code to select all the checkboxes placed inside the GridView column. Javascript code for this code has an advantage that no page refresh or postback event occurs to select all the checkboxes with a client side click event. Now the problem is how to perform the select all function at client side for server checkbox controls which are placed inside the GridView server control container.

HTML Code for GridView with Checkbox Controls

<asp:GridView ID="GridView1" 
    runat="server" 
    AutoGenerateColumns="False" 
    BorderStyle="Solid"
    CellPadding="4" 
    DataKeyNames="CategoryID" 
    BorderColor="Silver" 
    BorderWidth="1px"
    Width="300px">
    <Columns>
        <asp:TemplateField 
            HeaderText="Categories" 
            HeaderStyle-HorizontalAlign="Left">
            <HeaderTemplate>
                <asp:CheckBox ID="chkSelectAll" 
                    runat="server" 
                    Text="SelectAll" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox ID="chk1" 
                runat="server" 
                Text='<%#DataBinder.Eval(Container.DataItem,"categoryID") & " " & DataBinder.Eval(Container.DataItem,"categoryName") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <HeaderStyle HorizontalAlign="Left" BackColor="#f0f0f0" />
</asp:GridView>

In the above HTML code for GridView with Checkbox layout you can see that there are 2 checkboxes placed inside the GridView control. 1st checkbox control has been placed inside the HeaderTemplate of TemplateField column. This checkbox will perform the function to select all the checkboxes rendered inside the row items of GridView. 2nd checkbox has been placed inside the ItemTemplate of same TemplateField column that will generate row items like a checkbox list. Next we need a javascript function to develop the functionality of select all checkboxes at once. Few lines of VB.Net server side code are also required to attach the javascript function to the onclick event of checkbox server control.

JavaScript Code to Select All CheckBox Controls

<script type="text/javascript">

function selectAll(obj1,obj2)
{
    var checkboxIds = new String();
    checkboxIds = obj1;
        
    var arrIds = new Array();
    arrIds = checkboxIds.split('|');
        
    for(var i=0;i<arrIds.length;i++)
    {
        document.getElementById(arrIds[i]).checked = obj2.checked;
    }
}

</script>

Above javascript SelectAll function accepts two parameters as obj1 and obj2. obj1 accepts the pipes "|" separated string value as client side IDs of checkbox server controls placed inside the GridView control. obj2 accepts the client side ID of the checkbox control placed inside the HeaderTemplate to apply the same checkbox state to the each checkbox control inside the GridView control.

VB.Net Code to Attach the JavaScript Function to CheckBox Control

Public Sub bindGridViewCategories()
    ' string variable to store the connection string
    ' defined in appsettings section of web.config file.
    Dim connStr As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

    ' object created for SqlConnection Class.
    Dim mySQLconnection As New SqlConnection(connStr)

    ' if condition that can be used to check the sql connection
    ' whether it is already open or not.
    If mySQLconnection.State = ConnectionState.Closed Then mySQLconnection.Open()

    Dim mySqlCommand As New SqlCommand("select categoryId, categoryName from categories", mySQLconnection)
    Dim mySqlAdapter As New SqlDataAdapter(mySqlCommand)
    Dim myDataSet As New DataSet()
    mySqlAdapter.Fill(myDataSet)

    GridView1.DataSource = myDataSet
    GridView1.DataBind()

    Dim chk As CheckBox
    Dim checkboxIdsList As New List(Of String)

    For Each rowItem As GridViewRow In GridView1.Rows
        chk = CType(rowItem.Cells(0).FindControl("chk1"), CheckBox)
        checkboxIdsList.Add(chk.ClientID)
    Next

    Dim checkboxIds As String = String.Join("|", checkboxIdsList.ToArray())

    ' attach javascript function to select all the checkbox items
    CType(GridView1.HeaderRow.Cells(0) _
            .FindControl("chkSelectAll"), CheckBox) _
            .Attributes.Add("onclick",
                            "selectAll('" & checkboxIds & "',this)")

    ' if condition that can be used to check the sql connection
    ' if it is open then close it.
    If mySQLconnection.State = ConnectionState.Open Then mySQLconnection.Close()
End Sub

In the above VB.Net code, For each loop has been used to collect the ClientID of each checkbox control placed the GridView control. We have used a generic List type collection of strings to store the ClientID of checkbox controls. The VB.Net string.Join function has been used next to concatenate the list items into a single string separated with "|" operator so that it could be passed to the JavaScript function. The last logical code statement has the code to attach an attribute to the checkbox control placed inside the HeaderTemplate of the GridView control. We have attached the JavaScript function to the header checkbox with its "onclick" client side event to update the state of checkbox controls at client side without refreshing the whole web page.

Output:

Get the output for above discussed code from the following link:

VB.Net GridView Checkbox Select All using JavaScript

Continue to next tutorial: Maintaining the checkbox state while GridView paging using VB.Net - 1 to learn how to maintain the state of the checkbox control after performing the paging action on ASP.Net GridView control using VB.Net code.

0 Responses to "GridView CheckBox Select All using JavaScript and VB.Net"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers