I want to add a class name to some of my BoundFields in the GridView control; so that once the GridView is data-bound and rendered I can obtain something like:
<td class="Tag1">Some data came from data source</td>
The purpose of doing such a thing is to be able to find all the elements that are "Tag1" in this way:
var allTag1td = $('td.Tag1');
So, how can I add this class to the BoundField so that it is rendered in this way?
Add the ItemStyle property to your field:
<asp:BoundField DataField="Count" HeaderText="Count">
<ItemStyle CssClass="yourclass"></ItemStyle>
</asp:BoundField>
Can you not directly set the itemstyle property of your boundfield in the aspx?
(TableItemstyle has a CssClass property)
<asp:BoundField ItemStyle-CssClass="Tag1"/>
See:
You can set a row's cell CssClass
property to Tag1
when the row's created (RowCreated
event).
Page.aspx:
<asp:GridView OnRowCreated="grid_RowCreated" AutoGenerateColumns="true" runat="server" ID="grid"></asp:GridView>
Code-behind file, Page.aspx.cs:
protected void grid_RowCreated(object sender, GridViewRowEventArgs e) {
foreach (TableCell cell in e.Row.Cells)
cell.CssClass = "Tag1";
}
The code will set the class
attribute of each td
in your table to Tag1
; the markup of the rendered page will look like the one you're looking for:
<td class="Tag1"></td>
<td class="Tag1"></td>
...
You can convert to TemplateField then use a Label and Add any style you want.
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Field") %>' CssClass="YourStyle" />
</ItemTemplate>
</asp:TemplateField>
OR
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Field") %>' Style="line-height: 1.4" />
</ItemTemplate>
</asp:TemplateField>
It works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With