How to dynamically assign a BackColor to a GridView row?
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.
开发者_如何学GoThe 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.
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
精彩评论