ASP.NET/VB.NET Sample - Using a check box in a datagrid

VB.NET applications provide a checkbox selection for a datagrid column where the ASP.NET component does not. This code example shows the ASP.NET form code and the VB code behind for placing a checkbox in a datagrid and then capturing its value serverside.

JavaScript to set the checkbox values when select all is checked and unchecked

< script language="javascript" type="text/javascript" >

function select_deselectAll (chkVal, idVal) 
{
var frm = document.forms[0];
var mynum=0;
// Loop through all elements
for (i=0; i<frm.length; i++)
{
// Look for our Header Template's Checkbox
if (idVal.indexOf ('myselectall') != -1)
{
// Check if main checkbox is checked, then select or deselect datagrid checkboxes
if(chkVal == true)
{
frm.elements[i].checked = true;
}
else
{
frm.elements[i].checked = false;
}
// Work here with the Item Template's multiple checkboxes
}
else if (idVal.indexOf ('myselect') != -1)
{
if(frm.elements[i].name.indexOf ('myselectall') != -1)
{
mynum = i
}
// Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
if(frm.elements[i].checked == false)
{
frm.elements[mynum].checked = false;
}

}
}
}
</script>

Web form code snippet - goes in the column declaration section of the datagrid code

 <asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox Checked="False" Runat="server" ID="myselectall" OnClick="javascript: return select_deselectAll (this.checked, this.id);"></asp:CheckBox>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox Checked="False" Runat="server" ID="myselect" OnClick="javascript: return select_deselectAll (this.checked, this.id);"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn> | Vb code behind to capture the check box state (checked of unchecked) and act on that condition. Private Sub SomeObject_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles SomeObject.Click Dim myitem As ListItem Dim i, k As Integer i = 0 k = 0 CheckBoxList1.Visible = True DataGrid1.Visible = False For Each myitem In CheckBoxList1.Items If myitem.Selected Then <Do something> End If Next end sub