How to implement conditional formatting in a GridView

前端 未结 4 1365
礼貌的吻别
礼貌的吻别 2021-01-18 21:55

I have a GridView on my aspx page which displays a collection of objects defined by the following class

public class Item
{
    public string ItemName{get; s         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-18 22:41

    Not sure if you can use a BoundField, but if you change it to a TemplateField you could use a formatting function like in this link.

    ie something like

    <%# FormatDataValue(DataBinder.Eval(Container.DataItem,"ItemValue")) %>
    

    Then in your codebehind, you can add a Protected Function

    Protected Function FormatDataValue(val as object) As String
        'custom enter code hereformatting goes here
    End Function
    

    Or you could do something in the OnRowCreated event of the gridview, like in this link

    
    

    this function is conditional formatting based on whether or not the datavalue is null/is a double

    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            Object ob = drv["ItemValue"];
    
    
            if (!Convert.IsDBNull(ob) )
            {
                double dVal = 0f;
                 if (Double.TryParse(ob.ToString(), out dVal))
                 {
                     if (dVal > 3f)
                     {
                         TableCell cell = e.Row.Cells[1];
                         cell.CssClass = "heavyrow";
                         cell.BackColor = System.Drawing.Color.Orange;
                     }
                 }
            }
        }
    }
    

提交回复
热议问题