Selectively apply css to a row in a gridview

前端 未结 2 1471
面向向阳花
面向向阳花 2020-12-08 21:41

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.:

Gri

2条回答
  •  佛祖请我去吃肉
    2020-12-08 22:29

    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

提交回复
热议问题