使用GridView和DataSource控件连接数据库,select语句为:select id,productname,price from product
请问如何实现符合price >100的记录在GridView中相应price单元格变色?

解决方案 »

  1.   

    在GridView的binding事件中写判断代码
      

  2.   

    RowDataBound 事件,GridView每绑定一行就会触发一次这个事件,在这里写代码判断当前绑定行(e.Row.Cells[1].Text)是否>100
      

  3.   

    <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <%# Convert.ToInt32(Eval("UnitPrice")) > 100 ? "<span style='color:Red'>" + Eval("UnitPrice").ToString() + "</span>": Eval("UnitPrice").ToString() %>
                </ItemTemplate>
            </asp:TemplateField>
    </Columns>
      

  4.   

    amandag的方式够精巧。其实按最‘正规’的写法应该是在GridView.RowDataBound里写。
    <style type="text/css">
            .cellStyle { background-color:Maroon; color:White; font-weight:bold; }
    </style>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
             DataRowView drv = (DataRowView)e.Row.DataItem;
             if (!Convert.IsDBNull(drv["UnitPrice"]) && Convert.ToDecimal(drv["UnitPrice"]) > 30m) //考虑到UnitPrice字段可能有空值的情况
             {
                   e.Row.Cells[2].CssClass = "cellStyle"; //第三列
             }
          }
    }