GridView - RowCreated EventHandler doesn't work if page IsPostBack

P

Paul

Hello All,

I am trying to use the following RowCreated Event Handler to make the
BackColor of a cell different if it has a particular value.

protected void GridView1_RowCreated(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{

object cellValue = DataBinder.Eval(e.Row.DataItem,
"Primary Diagnosis");
if(cellValue != null)
{

if (cellValue.Equals("Unknown or Service Recipient
Declined"))
{
e.Row.Cells[1].BackColor = Color.Yellow;
}

}
}
}

The page works as expected the first time it is loaded. But if it is a
PostBack cellValue is null, so the code to color the cells BackColor
does not run. If I take out condition "if(cellValue != null) I get an
error message. How can I use the RowCreated Event handler to control
the BackColor of cells even when it is a PostBack.

Help is always appreciated. Thanks,

Paul
 
E

Eliyahu Goldin

Paul,

Two things:

1. Use RowDataBound event instead of RowCreated.

2. There is no need to call DataBinder.Eval. You can use e.Row.DataItem with
typecasting. If your datasource is a datatable, you can write something like

object cellValue = (DataRowView)e.Row.DataItem["Primary Diagnosis"];

--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]
http://msmvps.com/blogs/egoldin
http://usableasp.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top