根据条件更改GridView行颜色

Sun*_*mal 40 c# asp.net

我想根据某些条件更改gridview的特定行颜色,我使用ASP.NET和c#.谢谢.

Nil*_*iya 49

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Attributes.Add("style", "cursor:help;");
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Alternate)
    { 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {                
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#E56E94'");
            e.Row.BackColor = Color.FromName("#E56E94");                
        }           
    }
    else
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='gray'");
            e.Row.BackColor = Color.FromName("gray");                
        }           
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不是修改`Row`属性等,而是创建两个css类并且只改变`e.Row.CssClass`要好得多.更简单的代码可以更好地分离逻辑和视图. (3认同)

小智 27

protected void DrugGridView_RowDataBound(object sender, GridViewRowEventArgs e)

{
    // To check condition on integer value
    if (Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "Dosage")) == 50)
    {
      e.Row.BackColor = System.Drawing.Color.Cyan;
    }
}
Run Code Online (Sandbox Code Playgroud)


ash*_*lia 9

GridView1_RowDataBound为GridView 创建事件.

//Check if it is not header or footer row
if (e.Row.RowType == DataControlRowType.DataRow)
{
    //Check your condition here
    If(Condition True)
    {
        e.Row.BackColor = Drawing.Color.Red // This will make row back color red
    }
}
Run Code Online (Sandbox Code Playgroud)