Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Validation & remeber values of selected checkboxes in grid controls using javascript

0.00/5 (No votes)
31 Jan 2010 1  
This article explains how to make validation on checkboxes and remember the selected checkboxes' values in DataGrid/GridView etc, together. This will

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

This article explains how to make validation on checkboxes and remember the selected checkboxes' values in DataGrid/GridView etc, together. This will make xecution faster as we wont have to use FindControl method of grid controls.

I have always been in need of this and used this approach in almost every project.

//ASPX Code

<asp:GridView runat="server" AutoGenrateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Select">

<ItemTemplate>

<input type="checkbox" id="chk_<%#Eval("id")%>" value="<%#Eval("id")%>" />

</ItemTemplate>

</asp:TemplateField>

...... (other column templates)

</Columns>

</asp:GridView>

Example: Suppose in control panel we are displaying registered users of the site in grid controls. And we want to provide a facility to activate/deactivate/delete these users by checking the appropriate checkboxes.

//JavaScript code

function getCheckboxSelection()
{
    var strID="";
    for (i=0; i < document.forms[0].elements.length; i++)
    {
        if ((document.forms[0].elements[i].type == 'checkbox') && (document.forms[0].elements[i].id.indexOf(ObjID) > -1))
        {
            if (document.forms[0].elements[i].checked == true)
            strID += document.forms[0].elements[i].value+",";
        }
    }
    if(strID!="") strID = strID.substring(0,strID.length-1);
    return strID;
}

If strID is "" then we can display error saying that "no checkbox was selected" else we can store strID (comma separated values of selected checkboxes) in HiddenField on aspx page which will be accessed in code behind to performed some operations on these selected values.

 

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here