Say I have a datagrid with just one column, several rows, with a checkbox in each row.I want to build a save function that saves each checked item to the database.I also want to be able to click anywhere on the datagrid row and have that check/uncheck the box for me, which \I will achieve with javascript and html events.
public sub save(userID as int16)
Dim item As DataGridItem = Nothing
Dim userGroupID As Int16 = 0
Dim checked As Boolean = False
'First I would delete all records from the database table with this userID
'to clear all the old records (or the SaveToDatabase could remove duplicates if already in db)
For i As Int16 = 0 To grdUserGroups.Items.Count - 1
item = grdUserGroups.Items(i)
checked = CType(item.FindControl("chkUserGroup"), CheckBox).Checked
If checked = True Then
userGroupID = Val(CType(item.FindControl("lblID"), Label).Text.Trim)
If userID > 0 Then
SaveToDatabase(userID, userGroupID)
End If
End If
Next
end sub
Protected Sub grdUserGroups_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles grdUserGroups.ItemDataBound
Select Case e.Item.ItemType
Case ListItemType.AlternatingItem, ListItemType.Item
'If the dg row is clicked anywhere, check/uncheck the box with javascript
Dim chk As CheckBox = CType(e.Item.FindControl("chkUserGroup"), CheckBox)
chk.Attributes.Add("onmouseover", "allowCheck = false;")
chk.Attributes.Add("onmouseout", "allowCheck = true;")
e.Item.Attributes.Add("onclick", "toggleChkUserGroup('" & chk.ClientID & "');")
End Select
End Sub
ctl03_grdUserGroups_ctl01_chkUserGroup
ctl03_grdUserGroups_ctl02_chkUserGroup
ctl03_grdUserGroups_ctl03_chkUserGroup
ctl03_grdUserGroups_ctl04_chkUserGroup
var allowCheck = false;
function toggleChkUserGroup(clientId) {
//clientId look like ctl03_grdUserGroups_ctl04_chkUserGroup
if (allowCheck == true) {
chk = document.getElementById(clientId);
if (chk.checked == true) {
chk.checked = false;
} else {
chk.checked = true;
}
}
}