I have a GridView control in an asp.net 3.5 webpage, the following code executes in the RowDataBound Event and it changes the background color and font color, once a value in the columns: RegWaitTime, and TotalWegTime is bigger than 30,
The value comes from two computated columns in sql server which returns the result from the substraction from other two columns, the problem here is that if the values are NULL in those column, I will get and error on the code that changes the color,, sorry my english , please let me know if you need me to clarify my requirement,
Thanks in advance
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Change Wait Time Cell Rows CHECK THE LOGIC HERE
if (e.Row.RowType == DataControlRowType.DataRow)
{
// This line will get the reference to the underlying row
DataRowView _row = (DataRowView)e.Row.DataItem;
if (_row != null)
{
// get the field value which you want to compare and
// convert to the corresponding data type
// i assume the fieldName is of int type
int _field = Convert.ToInt32(_row.Row["RegWaitTime"]);
if (_field > 30)
{
e.Row.Cells[9].BackColor = System.Drawing.Color.Red;
e.Row.Cells[9].Style.Add("color", "white");
}
else
e.Row.Cells[9].BackColor = System.Drawing.Color.Green;
e.Row.Cells[9].Style.Add("color", "white");
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
// This line will get the reference to the underlying row
DataRowView _row2 = (DataRowView)e.Row.DataItem;
if (_row2 != null)
{
// get the field value which you want to compare and
// convert to the corresponding data type
// i assume the fieldName is of int type
int _field = Convert.ToInt32(_row2.Row["TotalRegTime"]);
if (_field > 30)
{
e.Row.Cells[10].BackColor = System.Drawing.Color.Red;
e.Row.Cells[10].Style.Add("color", "white");
}
else
e.Row.Cells[10].BackColor = System.Drawing.Color.Green;
e.Row.Cells[10].Style.Add("color", "white");
}
}
}
You need to change the conversion code to:
The reason you need this is that if
_row.Row["RegWaitTime"]isNULL, the actual value you’ll get isDBNull.Valuewhich will choke withConvert.ToInt32throwing anInvalidCastExceptionsince object cannot be cast from DBNull to other types.Another alternative would be: