In Foliotek, there are a lot of instances where we have a table with a check box column that allows users to select rows and do some sort of action to them. This leads to a lot of redundancy in our markup and code. For example, here is what our datagrids looked like when we placed a checkbox in them (we’re using a custom server control for our datagrid):
Datagrid with a checkbox
<Components:ExtendedDataGrid runat="server" id="dgItems"> <Columns> <asp:TemplateColumn> <HeaderTemplate> <input class="check" onclick="FLTK.checkbox.selectAll(this.checked, 'chkSelect');" type="checkbox" /> </HeaderTemplate> <ItemTemplate> <input class="check" type="checkbox" id="chkSelect" runat="server" /> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn> <ItemTemplate> <%# Eval("ItemName") %> </ItemTemplate> </asp:TemplateColumn> </Columns> </Components:ExtendedDataGrid>
Check All JS
Here’s our javascript code that controls the select/deselect all functionality. See this blog post in reference to the :asp() selector, and this post for more information on the select all functionality.
FLTK.checkbox = { selectAll: function (checked, endingwith) { var $checkboxes = $(":asp(" + endingwith + ")"); // we don't want to check a box that is hidden on the page if (checked) { $checkboxes = $checkboxes.filter(":visible").not(":disabled"); } $checkboxes.attr("checked", checked); } }
Get selected rows (C#)
Then, to get the selected items in the code behind and perform some action on them, we’d have to do the following:
foreach(DataGridItem item in dgItems.Items) { if(((HtmlInputCheckBox)item.FindControl("chkSelect")).Checked) { // perform action } } // which can also be written as... foreach(DataGridItem in dgItems.Items.Cast<DataGridItem>().Where(i => ((HtmlInputCheckBox)i.FindControl("chkSelect")).Checked)) { // perform action }
Creating the Custom Datagrid Checkbox Column
Since the above code and markup is used so frequently in Foliotek, we wanted to abstract this logic into something that was easier to use. As I stated above, we use a custom server control that extends the datagrid control, but if you don’t have a custom server control it shouldn’t be hard to create one.
I would suggest reading up on custom server controls, if you’re interested in how the following code works.
Below is our server controls for the custom DataGrid, CheckBoxColumn, and CheckBoxTemplate. Keep in mind the Checked and VisibilityDataField on the CheckBoxColumn are optional.
namespace Components { // here is our custom datagrid control public class ExtendedDataGrid : DataGrid { public IEnumerable<DataGridItem> GetSelectedItems() { if (!this.Columns.Cast<DataGridColumn>().Any(c => c is CheckBoxColumn)) { throw new Exception("ExtendedDataGrid must have a 'CheckBoxColumn' in order to use GetSelectedItems"); } return this.Items.Cast<DataGridItem>().Where(i => ((CheckBox)i.FindControl("cb_" + this.ID)).Checked); } } // Usage: <Components:CheckBoxColumn Checked="false" VisibilityDataField="Show"></Components:CheckBoxColumn> // Alternative Usage: VisiblityDataField="!Hide" public class CheckBoxColumn : TemplateColumn { public string VisibilityDataField { get; set; } public bool Checked { get; set; } public CheckBoxColumn() : base() { } public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType) { if (this.Owner != null) { this.HeaderTemplate = new CheckBoxTemplate(this.Owner.ID, VisibilityDataField, true, Checked); this.ItemTemplate = new CheckBoxTemplate(this.Owner.ID, VisibilityDataField, false, Checked); } base.InitializeCell(cell, columnIndex, itemType); } } public class CheckBoxTemplate : ITemplate { private string _tableID; private bool _isHeader; private string _visibilityDataField; private bool _isChecked; public CheckBoxTemplate(string tableID, string visibilityDataField, bool isHeader, bool isChecked) { _tableID = tableID; _isHeader = isHeader; _visibilityDataField = visibilityDataField; _isChecked = isChecked; } public void InstantiateIn(Control c) { if (_isHeader) { // If the template container is the header, then we need to add the check all functionality to the checkbox HtmlInputCheckBox input = new HtmlInputCheckBox(); input.Attributes["onclick"] = "FLTK.checkbox.selectAll(this.checked, 'cb_" + this._tableID + "');"; // This id is determined below. input.Checked = _isChecked; // Set the checked status by default c.Controls.Add(input); } else { CheckBox cb = new CheckBox(); cb.ID = "cb_" + this._tableID; if (!String.IsNullOrEmpty(_visibilityDataField)) { cb.DataBinding += new EventHandler(cb_DataBinding); // doing this in the databind event allows us to access properties in the dataitem. } cb.Checked = _isChecked; c.Controls.Add(cb); } } void cb_DataBinding(object sender, EventArgs e) { var cb = (CheckBox)sender; var dataitem = ((DataGridItem)cb.NamingContainer).DataItem; bool show = true; if (!String.IsNullOrEmpty(this._visibilityDataField)) { bool not = this._visibilityDataField.StartsWith("!"); show = (bool)DataBinder.Eval(dataitem, (not ? this._visibilityDataField.Substring(1) : this._visibilityDataField)); show = not ? !show : show; } cb.Visible = show; } } }
New markup and code behind
Here’s our new markup. Notice how we only have one line now for the checkbox column, compared to 8 lines before.
<Components:ExtendedDataGrid runat="server" id="dgItems"> <Columns> <Components:CheckBoxColumn></Components:CheckBoxColumn> <asp:TemplateColumn> <ItemTemplate> <%# Eval("ItemName") %> </ItemTemplate> </asp:TemplateColum> </Columns> </Components:ExtendedDataGrid>
… and our code behind, which definitely simplifies the prior statement…
foreach(DataGridItem item in dgItems.GetSelectedItems()) { //perform action }