Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a CSS class to a BoundField, so I can find it with jQuery?

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?

like image 521
pencilCake Avatar asked Aug 12 '10 12:08

pencilCake


4 Answers

Add the ItemStyle property to your field:

<asp:BoundField DataField="Count" HeaderText="Count">
    <ItemStyle CssClass="yourclass"></ItemStyle>
</asp:BoundField>
like image 196
Ralph Willgoss Avatar answered Nov 07 '22 19:11

Ralph Willgoss


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:

  • http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datacontrolfield.itemstyle.aspx
  • http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.tableitemstyle_properties.aspx
like image 42
Tobiasopdenbrouw Avatar answered Nov 07 '22 21:11

Tobiasopdenbrouw


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>
...
like image 6
Giuseppe Accaputo Avatar answered Nov 07 '22 20:11

Giuseppe Accaputo


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.

like image 4
user3473248 Avatar answered Nov 07 '22 21:11

user3473248