根据条件动态更改GridView Row的背景颜色

时间:2015-04-30 12:49:47

标签: c# asp.net gridview

我正在尝试根据gridview中的标签值更改gridview行的颜色。我在gridview中有结束日期值,所以如果结束日期<我想要更改背景颜色。今天的约会。

    <asp:GridView ID="gv_profile" runat="server" AutoGenerateColumns="false" Width="300px" OnRowDataBound="OnRowDataBound" DataKeyNames="ID"  >

  <Columns>

    <asp:TemplateField ItemStyle-Width="10px" HeaderText="ID" >
     <ItemTemplate>
      <asp:Label ID="LblID" runat="server" Text='<%# Eval("ID")%>'></asp:Label>
       </ItemTemplate>
         </asp:TemplateField>


    <asp:TemplateField ItemStyle-Width="50px" HeaderText="End Date">
      <ItemTemplate>
      <asp:Label ID="lblEndDate" runat="server" Text='<%# Eval("End_Date", "{0: yyyy-MM-dd}") %>'></asp:Label>
       </ItemTemplate>
          </asp:TemplateField>

 </Columns>

  </asp:GridView>

背后的代码

  protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
   {
        if (e.Row.RowType == DataControlRowType.DataRow)
         {

         }
     }

3 个答案:

答案 0 :(得分:2)

应该符合您的需求

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && !((e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) || (e.Row.RowState == DataControlRowState.Edit)))
    {
        Label lblEndDate = (Label)e.Row.FindControl("lblEndDate");
        DateTime EndDate = DateTime.Parse(lblEndDate.Text);
        if (EndDate<DateTime.Today)
        {
            e.Row.BackColor = System.Drawing.Color.MistyRose;
        }
    }

}

答案 1 :(得分:0)

 protected void grdView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Attributes.Add("onmouseover", "MouseEvents(this, event)");
            e.Row.Cells[0].Attributes.Add("onmouseout", "MouseEvents(this, event)");


            if ((lblhidisinsert.Value == "1") )
            {
                e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#ecf8ec");
            }           
        }
    }

答案 2 :(得分:0)

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int id = Convert.ToInt32(e.Row.Cells[1].Text);
        if (id > 0)
        {
            e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            e.Row.Cells[1].Text = Math.Abs(id).ToString();
            e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
        }
    }