Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DataGrid: Changing color of a row 1

Status
Not open for further replies.

abds

Programmer
Dec 13, 2000
46
0
0
US
I would like to change the background color of rows that have a special value in a particular column.
Example: Most rows have a value of 1 in the status column, some do not.
I would like to render the rows that do not have a status of 1 in a different color.
Can this be done using a datagrid?
 
Yes, this can be done. Assumming that you are binding your grid: set the DataKeyField property to "status" item of your recordset:
<asp:DataGrid id=myGrid DataKeyField=&quot;status&quot;>

Register an event handler for Ithe temDataBound event of your grid in code behind:
private void InitializeComponent()
{
this.myGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.myGrid_ItemDataBound);
}

private void myGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.SelectedItem)
{
int key = Convert.ToInt32(myGrid.DataKeys[(int)e.Item.ItemIndex]);
if(key < 1)
{
e.Item.BackColor = Color.Green;
}
// if status > 0, then row color will be set to whatever default color is
}
}
 
Thank you very much LV.

I simplified it slightly by adding in not only the DataKeyField, but also OnItemDataBound=&quot;myGrid_ItemDataBound&quot;.

I then added your subroutine (in Visual Basic):

Public Sub myGrid_ItemDataBound(ByVal sender As System.Object, ByVal e As DataGridItemEventArgs)
If ((e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Or (e.Item.ItemType = ListItemType.SelectedItem)) Then
Dim key As Integer
key = CInt(myGrid.DataKeys(e.Item.ItemIndex))
If key <> 1 Then
e.Item.BackColor = Color.Green
End If
End If
End Sub
 
Sweet! It's another way of registering an event handler. Glad it helped.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top