Showing posts with label DataGrid. Show all posts
Showing posts with label DataGrid. Show all posts

Tuesday, April 14, 2009

How to change the style of DataGrid columns during the runtime (Apply styles to DataGrid columns at runtime)

Recently I was asked to do a task where it needed to change the style of a DataGrid column item during the runtime. I tried in various ways and finally came up with the solution listed below. The requirement was to change the applied style of a DataGridColumnTemplate and apply a new style. We are using the Telerik RadGrid in our development but I am quite sure that this can be applied to the normal grid as well. The style needed to be applied to a LinkButton which was inside the DataGridColumnTemplate.

I am using the ItemDataBound of the DataGrid control to apply the changes. First I am selecting the particular row to be edited. In this case, the row in which the style needs to be changed. In this example, I am first checking whether the item provided to the event is a GridDataItem. In this example, I am only changing the style of rows, which meets a specific criterion (I am checking whether a particular record is ‘inactive’). Thereafter I am setting the style of the entire row to a new style (item.CssClass = "disabledrow";).

Each DataGridColumnTemplate has a controls collection. We need to select the required control from the collection (if (control.ID == "imgSearchView")). Then cast the control to the required control and apply the style.

LinkButton linkButton = null;
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
if (item["activecolumn"].Text.ToString() == EntityActiveStatus.Inactive.ToString())
{
item.CssClass = "disabledrow";

foreach (Control control in item["viewcolumn"].Controls)
{
if (control.ID == "imgSearchView")
{
linkButton = (LinkButton)control;
linkButton.CssClass = "btnViewGray";
}
}

foreach (Control control in item["editcolumn"].Controls)
{
if (control.ID == "imgSearchEdit")
{
linkButton = (LinkButton)control;
linkButton.CssClass = "btnEditGray";
}
}

foreach (Control control in item["deletecolumn"].Controls)
{
if (control.ID == "imgSearchDelete")
{
linkButton = (LinkButton)control;
linkButton.CssClass = "btnDeactivateGray";
linkButton.ToolTip = "Activate";
}
}
}
}

Please leave a comment or contact me at my email address if you have any concerns.