Click here to Skip to main content
Click here to Skip to main content

Conditional Formatting ASP.NET DataGrid Columns

By , 21 Apr 2003
 
Prize winner in Competition "ASP.NET Mar 2003"
Sample Image - GridColumnFormatting.gif

Like our previous article, How to remove DataGrid column, this article will try to answer another most frequently asked question about DataGrid controls, how can I conditionally format columns of a data grid control at run time? Believe it or not the answer to this question is very straight forward. When you call DataBind on a DataGrid control or for that matter whenever a grid gets bound to its datasource, ASP.Net framework fires ItemDataBound event. You can add an event handler for this event to take control of the rendering of DataGrid control.

The key to the solution is capturing ItemDataBound event. When the page recieves this event, complete information about the data row is available in DataGridItemEventArgs parameter of the event handler. Item property of this parameter contains information about the table rows and cells that will get rendered on the page. This parameter also contains the information about the DataItem that is being used to render information for the row. The data item corresponds to DataRowView object for that row's data. You can get the value for any given data field based on the field name or zero based index of data column.

For this article we have used the sample Northwind database and bound it to our DataGrid column.

private void OnNWDataBound(object sender, <BR>             System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item ||
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataRowView rv = (DataRowView)e.Item.DataItem;
        // Get fourth column value.
        Int32 nUnitsInStock = Convert.ToInt32(rv.Row.ItemArray[4]);
        if (nUnitsInStock < 20)
        {
           e.Item.Cells[4].BackColor = Color.Red;
        }
    }
}
                        

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Softomatix
Web Developer
United States United States
Member
To learn more about us, Please visit us at http://www.netomatix.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey7 Feb '12 - 19:26 
Nice
Generalbackground imagemembermarko jovanovic7 Apr '06 - 2:14 
i've tried to set background image for cell based on some condition with css
style but couldn't set cssclass attribute of the cell, is there way to do this
vb code:
e.item.cells(1).cssclass = "cellimg"
 
style.css:
.cell
{
background-image:url(images/img.gif);
}
what i do wrong?
 
roopyu
QuestionIs there any equivalent situation for WinForms?sussAnonymous14 Jun '05 - 2:41 
Hello,
How can I do the same for Winforms?
Could you please help me?
 
King Regards
Generalmulti Datagridsusstenzeel.24 Jul '04 - 1:36 
How We show Master record on one row and on the next row we show the detail of that master record in data grid using asp.net.
thanx
tenzeel.
GeneralHisussAnonymous12 Apr '04 - 18:58 
Is there any chance of changing the widht of the columns in datagrid.
 

GeneralDataGrid formating and Editing data in DataGridmemberbinmak21 Feb '04 - 3:06 
I am trying to change the orientation of the datagrid that I am using to edit data in a database from horizontal to vertical orientation. i.e. display database row data in a datagrid column. I have been able to use the edit template columns to edit data in the horizontal format but in the vertical format I am getting an the following Error Message: Type 'System.Web.UI.WebControls.TemplateColumn' does not have a property named 'asp:EditItemTemplate'.
 
I want to end up with the following format:
|COLUMN1 | COLUMN2 |
|Employee ID | [EditTextbox] |
|First Name | [EditTextbox] |
|Last Name | [EditTextbox] |
 
Instead of :
|Employee ID | First Name |Last Name |
|[EditTextbox] | [EditTextbox] |[editTextbox] |
 

 
Please help.
QuestionHow this method gets called ?memberInnovatus13 Feb '04 - 8:07 
You forgot to show us how this method gets called. I dont understand how to trigger this method.
AnswerRe: How this method gets called ?memberthomashungnguyen4 Nov '05 - 3:08 
For the above example just do the following:
 
In the private void InitializeComponent()
 
Add:
this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnNWDataBound);
 

where DataGrid1, refers to the ID of your datagrid ... i.e. if you created a datagrid named MyGrid
, use this.MyGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnNWDataBound);
 
this.OnNWDataBound <--- replace this with your own method name if you like. Whenever ItemDataBound event occurs, it will call this method.
 
hopes this help Smile | :)
 

-- modified at 9:13 Friday 4th November, 2005
GeneralInvalidCastExceptionmemberlewinpj27 Nov '03 - 2:40 
An InvalidCastException gets thrown when I try this code on line:
DataRowView rv = (DataRowView)e.Item.DataItem;
 
Any ideas ?
GeneralChanging a Cells color based on another cells valuemembercdwaddell20 Aug '03 - 2:36 
We want to change the color of a previous cell based on the value in the current cell. For example, say we are ranking items as they are read into the datagrid. We have several columns of data we want to rank for first and second place. Once we encounter a value that is greater than the previous high value we would like to change the previous high values cell color to yellow and the new high cells color to green. For example column 1 in the following table would have 12 highlighted in green and 10 highlighted in yellow. See the following table. Column 2 would have 11 highlighted green and the two 10 highlighted yellow. and finally column 3 would have 14 green and 10 yellow.
 
User Name 1 2 3 Total
PLayer1 9 10 14 33
Player2 12 10 7 29
Player3 7 11 10 28
Player4 10 7 6 23

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 22 Apr 2003
Article Copyright 2003 by Softomatix
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid