Check all function for Datagrids

I had the need to create a datagrid check all function, similar to those that you see in yahoo, gmail, hotmail etc.

My Datagrid looked like this;

<asp:datagrid id="dgList" Runat="server" width="600px" AutoGenerateColumns="False">
<Columns>
	<asp:TemplateColumn>
		<HeaderTemplate>
			<asp:CheckBox ID="chkAll" onclick="javascript:jsSelectAll('dgList','dgList__ctl1_chkAll');" runat="server" ToolTip="Select/Deselect All" AutoPostBack="false" />
		</HeaderTemplate>
		<ItemTemplate>
			<asp:CheckBox ID="chkSelect" Runat="server"></asp:CheckBox>
		</ItemTemplate>
	</asp:TemplateColumn>
	<asp:BoundColumn DataField="col1" HeaderText="col1"></asp:BoundColumn>
	<asp:BoundColumn DataField="col2" HeaderText="col2"></asp:BoundColumn>
</Columns>
</asp:datagrid>

With the datagrid code above, make sure you modify the jsSelectAll parameters!
1st var: The name of your datagrid (In my example, dgList)
2nd var: The name of your check all checkbox

I used a javascript function that loops through all the checkboxes within the datagrid and selects/de-selects.

function jsSelectAll(datagridID, checkallID)
{
	var obj = document.getElementById(datagridID).all.tags("input");
	var blCheck = true;
	var chk = document.getElementById(checkallID);
	if (chk.checked == true)
		blCheck=true;
	else
		blCheck=false;
	for (var i=0; i<obj.length; i++){
		if (obj[i].type == "checkbox"){
			obj[i].checked = blCheck;
		}
	}
}

No related posts.



Leave a Reply