How do you apply an AlternatingItemStyle to a specific DataGrid TemplateColumn?

1k Views Asked by At

I've got a datagrid with 3 TemplateColumns, each containing a HeaderTemplate and an ItemTemplate. I put in a HeaderStyle, ItemStyle and AlternatingItemStyle for all 3 columns (so outside of the tags.

I then decided I want to apply a different ItemStyle specifically to the 3rd column, which I did by adding ItemStyle within the specific TemplateColumn. This worked fine, except that the AlternatingItemStyle that I still wanted was no longer applying. I thought I could simply add another AlternatingItemStyle within the specific TemplateColumn but this wasn't supported. I tried adding it in the code behind as well through the OnDataBinding command but AlternatingItemStyle doesn't appear under the Column property. Code is below:

<asp:DataGrid ID="dgErrors"
CssClass="cssErrors"
Caption="Errors"  
AutoGenerateColumns="false"
CellPadding="3"
runat="server">
    <Columns>
        <asp:TemplateColumn>
            <HeaderTemplate>Job Number</HeaderTemplate>
            <ItemTemplate><%# Eval("Job Number") %></ItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
            <HeaderTemplate>Error</HeaderTemplate>
            <ItemTemplate><%# Eval("Error") %></ItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
            <HeaderTemplate>Row Number</HeaderTemplate>
            <ItemTemplate><%# Eval("Line Number") %></ItemTemplate>
         <ItemStyle CssClass="TableItemStyleRowNo" />
         </asp:TemplateColumn>
     </Columns>

     <HeaderStyle CssClass="TableHeaderStyle" />
     <ItemStyle CssClass="TableItemStyle" />
     <AlternatingItemStyle CssClass="TableAlternatingItemStyle" />
 </asp:DataGrid>

My questions are; Firstly, how do you apply an AlternatingItemSyle to a specific TemplateColumn? Secondly, why is ItemStyle supported within a TemplateColumn but AlternatingItemStyle is not?

1

There are 1 best solutions below

3
On BEST ANSWER

The DataGrid's property

<ItemStyle CssClass="TableItemStyle" />
     <AlternatingItemStyle CssClass="TableAlternatingItemStyle" />

are applicable to the whole Row of Datagrid not on individual column.

To Achieve your requirement do following changes:

In your aspx page add OnItemDataBound property as follow :

 <asp:DataGrid ID="dgErrors"
CssClass="cssErrors"
Caption="Errors"  
AutoGenerateColumns="false"
CellPadding="3"
runat="server" 
OnItemDataBound = "dgErrors_ItemBound">

Add this code in your .cs page:

protected void dgErrors_ItemBound(Object sender, DataGridItemEventArgs e)
    {
            if (e.Item.ItemType == ListItemType.Item)
            {
                e.Item.Cells[0].CssClass = "TableItemStyleRowNo";
            }
            else if(e.Item.ItemType == ListItemType.AlternatingItem)
            {
                e.Item.Cells[0].CssClass = "AlternateTableItemStyleRowNo";
            }
    }