Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm looking for a way to selectively apply a CSS class to individual rows in a GridView based upon a property of the data bound item.

e.g.:

GridView's data source is a generic list of SummaryItems and SummaryItem has a property ShouldHighlight. When ShouldHighlight == true the CSS for the associated row should be set to highlighted

any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
412 views
Welcome To Ask or Share your Answers For Others

1 Answer

very easy

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;
        if (drv["ShouldHighlight"].ToString().ToLower() == "true")
            e.Row.CssClass = "highlighted";
    }
}

the code above works if you use a DataTable as DataSource

change to:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        myClass drv = (myClass)e.Row.DataItem;
        if (drv.ShouldHighlight)
            e.Row.CssClass = "highlighted";
    }
}

just for the example above when using generics:

public class myClass
{ 
    public Boolean ShouldHighlight
    { get; set; }
}

if you are working with Generics (List, Dictionary, etc)

keep in mind:

e.Row.dataItem

always return the entire object that you are populating the row with, so it is easy from here to manipulate the appearance of the data in the webpage.

you should use RowDataBound event that will trigger after the data is attached to the row object but not yet written the HTML code in the page, in this way you can check the ShouldHighlight value (I converted to a String cause I do not know the type, you can change it if you know it's a boolean value).

this code runs much faster than megakemp code cause you're not creating a List object and populated with the entire data source for each row...

P.S. take a look at this website, you can find several tutorials for your project using the GridView object


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...