How to dynamically assign a BackColor to a GridView row?

…衆ロ難τιáo~ 提交于 2019-12-13 17:30:22

问题


I'm working on an ASP.Net page containing a GridView, which is populated with customer orders returned by a stored procedure. What I'd like to do is dynamically change the backcolor of the GridView rows to indicate priority.

The stored procedure returns an integer indicating the records priority, I think I just need to translate the integer to a color, then make the GridView row display it.

The "making the GridView row display it" part is the one that's giving me a hard time.

What's the best way to do this? Can anyone give me an example?

Thanks in advance.


回答1:


Following a sample solution:

C#: aspx:

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" >
...
</asp:GridView>

codebehind:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int priority = (int)DataBinder.Eval(e.Row.DataItem, "priority");
        switch (priority)
        {
           case 1: 
              e.Row.BackColor = Drawing.Color.Green;
              break;
           case 2:
              e.Row.BackColor = Drawing.Color.Red;
              break;
           default:
              e.Row.BackColor = Drawing.Color.Black;
              break;
        }
    }
}

VB.Net codebehind:

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    Select Case e.Row.RowType
        Case DataControlRowType.DataRow
            Dim priority As Int32 = DirectCast(DataBinder.Eval(e.Row.DataItem, "priority"), Int32)
            Select Case priority
                Case 1
                    e.Row.BackColor = Drawing.Color.Green
                Case 2
                    e.Row.BackColor = Drawing.Color.Red
                Case Else
                    e.Row.BackColor = Drawing.Color.Black
            End Select
    End Select
End Sub


来源:https://stackoverflow.com/questions/4305268/how-to-dynamically-assign-a-backcolor-to-a-gridview-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!