Thursday, 10 July 2008

DataGridLinkButton

Programming language: C#

DataGridLinkButton
is a class that is often encountered when working with the headings in a datagrid containing BoundColumns; you typically come across it when you try to edit the columns during the _ItemCreated() or _ItemDataBound() events of the datagrid.

Problem: Checking for the type DataGridLinkButton can be tricky, because of the class being protected.

Solution: find the control by ordinal reference (i.e. in the header row of a datagrid cell there will only ever be one control... the column heading - which is a DataGridLinkButton, generated from the BoundColumn of the datagrid).
foreach(TableCell cell in e.Item.Cells)
desiredControl = cell.Controls[0]; // However, this will need to be cast, see code below.

So in the header row you can easily find the cells of the datagrid, which should contain one control each: the header per cell. If a header is found and it was created from a BoundColumn that is clickable (i.e. you've enabled sorting on the grid), then the control will be a DataGridLinkButton, which you can cast to a linkbutton.

Scenario: in mydatagrid_ItemDataBound() the event called when each datagrid line is created, I try to set a tooltip on each heading in the grid. The columns are dynamically shown and hidden and configured by each user individually; the tooltips are custom phrases that the client requested, so the ItemDataBound event is ideal for finding only those columns being displayed, finding the column name (see datagridLinkButtontext below) and then modifying the column.

Code:

protected void myDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
//Check if this is the header row of the grid:
if (e.Item.ItemType == ListItemType.Header)

//Loop through the columns (cells) of the header row
foreach(TableCell cell in e.Item.Cells)
{
string datagridLinkButtontext = string.Empty;
LinkButton lb = new LinkButton();
try
{
lb = (LinkButton)cell.Controls[0];
}
catch (InvalidCastException ex)
{
// do nothing if its not a linkbutton
}
if (lb != null) datagridLinkButtontext = lb.Text;
// now you can use the above text to determine which column you're working with,
// and do something with it, i.e as in my case set the tooltip:
cell.ToolTip = getTooltipForColumn(datagridLinkButtontext);
}
...
}

No comments: