Last post Jun 16, 2008 04:28 PM by b471code3
Mar 30, 2007 12:42 PM|macal_vm|LINK
Im trying to change the color of labels inside my gridview according to the text it contains.
So I tried this code:
protected void Page_Load(object sender, EventArgs e)
Label statslab = (Label)GridView1.FindControl("Label1");
string statstxt = statslab.Text;
if (statstxt == "Hold")
But I keep getting this error: "Object reference not set to an instance of an object."
What can I do to make it work?
Im using VWD and C#.
Mar 30, 2007 01:24 PM|stiletto|LINK
You have to do this kind of conditional formatting in the RowDataBound event (or your Grid's equivalent).
There, your code should have the right context to be able to find the Label and allow you to set the formatting.
Mar 30, 2007 01:29 PM|rumbafum|LINK
Mar 30, 2007 01:33 PM|macal_vm|LINK
doent matter where I put the code, I keep getting the same error msg on this line:
string statstxt = statslab.Text; -> "Object reference not set to an instance of an object."
Mar 30, 2007 05:00 PM|stiletto|LINK
In the GridView, you wouldn't get the Label using FindControl. You get the desried grid column by index.
Here's a tutorial link:
Mar 30, 2007 05:22 PM|rumbafum|LINK
To Change the label ForeColor i use this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
Label label = (Label)e.Row.FindControl("label");
label.ForeColor = Color.Red;
the label is inside a templatefield, itemtemplate right? with runat=server?
Mar 30, 2007 05:45 PM|stiletto|LINK
I'm not sure if that will get you close enough.
You might need to use e.Row.Cells[<Zero-based index of cell containing desired Label control>].FindControl.
Apr 02, 2007 12:20 PM|macal_vm|LINK
Apr 03, 2007 06:18 PM|rumbafum|LINK
Jun 13, 2008 08:53 PM|b471code3|LINK
I found this to be somewhat helpful! Thanks Rumbafum!
have close to the same situation although I need to look at a date in the row and compare it to the current date. So if the date in the specific row of the gridview is earlier than today the text or date should be red. If it is greater than Today the
text should be black.
Any thoughts on that?
Jun 16, 2008 04:14 PM|rumbafum|LINK
Sorry been away from the forum... Did you resolve your problem?
Jun 16, 2008 04:28 PM|b471code3|LINK
No actually, I have not had a chance to work on it the past few days. Do you understand what I am looking for?