Selecting/Deselecting all CheckBoxes inside a ListView In ASP.NET
Introduction:
This articles shows how to toggle checkboxes selection in a ListView using Javascript. Example in this article shows a ListView populated with random records with SelectAll functionality
Background:
Often we are required to
make one or multiple selection when different options are presented in a
databound control such as GridView, Repeater, ListView so on. It is
cumbersome to deselect each item individually when the selection has to
be cleared. ListView Header can contain a checkbox to select/deselect
items in all items of the ListView.
Markup:
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="text/javascript"> function toggleCheckBoxes(source) { var listView = document.getElementById('<%= ListView1.FindControl("table1").ClientID %>'); for (var i = 0; i < listView.rows.length; i++) { var inputs = listView.rows[i].getElementsByTagName('input'); for (var j = 0; j < inputs.length; j++) { if (inputs[j].type == "checkbox") inputs[j].checked = source.checked; } } } </script> </head> <body> <form id="form1" runat="server"> <asp:ListView runat="server" ID="ListView1"> <LayoutTemplate> <table runat="server" id="table1"> <tr> <td> <asp:CheckBox ID="cbSelectAll" runat="server" onclick="toggleCheckBoxes(this);" /> </td> <td> <b>Name</b> </td> </tr> <tr runat="server" id="itemPlaceholder"> </tr> </table> </LayoutTemplate> <ItemTemplate> <tr id="tr" runat="server"> <td> <asp:CheckBox ID="cbName" runat="server" /> </td> <td> <asp:Label ID="lblName" runat="server" Text='<%# Eval("name") %>'></asp:Label> </td> </tr> </ItemTemplate> </asp:ListView> </form> </body> </html>
CodeBehind:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ListView1.DataSource = Enumerable.Range(1, 10).Select(a => new { name = string.Format("Item {0}", a) }); ListView1.DataBind(); } }
Comments