Introduction
A recent project I was working on required a user to select a number of options from a list. Instead of using a mulit-select list box which didn't really fit into the design of the site we decided to make a reusable control that would add a checkbox to a DataGrid
.
Using the code
To use the checkbox column in a DataGrid
it's simply a matter of registering the tag at the top of the page:
<%@ Register TagPrefix="chkbox" Namespace="DataGridControls"
Assembly="DataGridCheckbox" %>
Then to add the checkbox column to the DataGrid
:
<asp:DataGrid ID="dgTestGrid" Runat="server" AutoGenerateColumns=True
border="0" width="50%">
<Columns>
<chkbox:CheckBoxColumn/>
</Columns>
</asp:DataGrid>
The CheckBoxColumn
class is pretty straight forward:
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace DataGridControls
{
public class CheckBoxColumn : DataGridColumn
{
public CheckBoxColumn(): base()
{
}
public override void InitializeCell(TableCell cell,
int columnIndex, ListItemType itemType)
{
base.InitializeCell(cell, columnIndex, itemType);
if( itemType == ListItemType.EditItem ||
itemType == ListItemType.Item ||
itemType == ListItemType.AlternatingItem ||
itemType == ListItemType.SelectedItem){
HtmlInputCheckBox checkbox = new HtmlInputCheckBox();
checkbox.ID = "checkboxCol";
cell.Controls.Add(checkbox);
}
}
public Int32[] SelectedIndexes
{
get
{
ArrayList selectedIndexList = new ArrayList();
foreach( DataGridItem item in this.Owner.Items )
{
HtmlInputCheckBox chkBox =
(HtmlInputCheckBox) item.FindControl("checkboxCol");
if ( chkBox != null && chkBox.Checked )
{
selectedIndexList.Add( item.ItemIndex );
}
}
return (Int32[])selectedIndexList.ToArray(typeof(
System.Int32 ) );
}
}
public object[] SelectedDataKeys
{
get
{
ArrayList dataKeyList = new ArrayList();
if(this.Owner.DataKeys.Count > 0)
{
foreach( Int32 selectedIndex in SelectedIndexes )
{
object DataKey =
(this.Owner.DataKeys[selectedIndex].ToString());
dataKeyList.Add(DataKey);
}
}
return (object[])dataKeyList.ToArray(typeof( object ) );
}
}
}
}
The class exposes 2 properties:
SelectedDataKeys:
Returns an ArrayList
with the DataKey
values
SelectedIndexes:
Returns an Int32[]
with the selectedIndex
values
To find out which checkbox has been selected:
protected void btnSubmit_Click(object sender, EventArgs e)
{
CheckBoxColumn chkbox = (CheckBoxColumn) dgTestGrid.Columns[0];
foreach(object datakeyfield in chkbox.SelectedDataKeys)
{
Response.Write(datakeyfield.ToString() + "<br>");
}
}
That's pretty much it, the DataKeyField
of the DataGrid
can be of any type. The sample I've included binds a DataTable
to the DataGrid
, you can change the DataKeyField
from "ID
" (int
) to "Name
" (string
) to see the code working with different types.