Introduction
This article describes a very simple way on how to use a CheckBox
in a GridView
or Repeater
in a manner similar to a Button
. This addresses the absence of the "CommandName
" property in a CheckBox
(CheckBoxField
).
Use Cases
A user goes through a list of items and needs a quick way to flag some of the items. For example, to indicate what items are completed (or verified). And maybe, update a DateCompleted
field on completion.
Unchecking in this case would change the status back to "Uncompleted" and maybe clear the DateCompleted
field.
Limitations of ASP.NET
The standard way of achieving similar results would be to use a Button
(or LinkButton
) with the CommandName
specified. The OnRowCommand
event handler for a GridView
(OnItemCommand
for a Repeater
) would handle the Click
on such a button. Then, you could easily access the record ID through e.CommandArgument
in these handlers.
In many of the cases like the one above, it would be preferable to use a CheckBox
instead – it is more compact and clearly indicates the current state. But since there is no "CommandName
" property for a CheckBox
and the CheckedChanged
event is not handled in OnRowCommand
(OnItemCommand
for a Repeater
), how can we get a record ID for the checkbox row, so we could properly handle the event?
Solution
It can't get any simpler than that: just assign a record ID as a Text
property for the CheckBox
and then hide the text through CSS.
Example
The example consists of a single ASPX file that has both a GridView
and a Repeater
that are bound to a DataTable
with columns {ItemID int, ItemDescription string, Flag bool}
.
Both the GridView
and the Repeater
have a TemplateField
containing a CheckBox
.
The whole trick is in Text='<%#Eval("ItemID")%>'
. Note that ItemID
is hidden because the Text
property for a CheckBox
is rendered as <label>
and we hide it with this style:
The event hander now can easily access the current record ID and the status of the CheckBox
: