Live Chat Icon For mobile
Live Chat Icon

How do I conditionally set the text color of a cell in my Datagrid based on the cell’s/fields’s value?

Platform: ASP.NET| Category: DataGrid

In the ItemDataBound event you can access the Cells() collection of the current Datagrid item (or row) and set it’s ForeColor.


<asp:DataGrid OnItemDataBound='ItemDB' id='DataGrid1' runat='server'></asp:DataGrid>

VB.NET


protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
If (e.Item.ItemType = ListItemType.Item Or _
                 e.Item.ItemType = ListItemType.AlternatingItem) Then
	If e.Item.DataItem(6) > 15 Then
		e.Item.Cells(6).ForeColor = System.Drawing.Color.Green
	Else
		e.Item.Cells(6).ForeColor = System.Drawing.Color.Red
	End If
End If
End Sub

C#


protected void ItemDB(object	 sender,  System.Web.UI.WebControls.DataGridItemEventArgs e) 
{
	if((e.Item.ItemType ==ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) )
	{
	if (Convert.ToInt16 (e.Item.Cells[6].Text) >15 )
		{
		e.Item.Cells[6].ForeColor = System.Drawing.Color.Green;
		}
	else
		{
		e.Item.Cells[6].ForeColor = System.Drawing.Color.Red;
		}
	}
}

In Cells[x]/Cells(x) x=> index number to the list of fields in the row.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.