我在asp.net 3.5网页中有一个GridView控件,下面的代码在RowDataBound事件中执行,它改变了背景颜色和字体颜色,一旦列中的值:RegWaitTime和TotalWegTime大于30,
该值来自sql server中的两个计算列,它返回来自其他两列的减法结果,这里的问题是如果这些列中的值为NULL,我将得到更改代码的错误颜色,对不起我的英文,如果你需要我澄清我的要求,请告诉我,
提前致谢
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");
}
}
}
答案 0 :(得分:0)
您需要将转换代码更改为:
int field=0;
if(int.TryParse(_row.Row["RegWaitTime"],out field))
{
if(field>30)
{
}
}
您需要这样做的原因是,如果_row.Row["RegWaitTime"]
为NULL
,则您获得的实际值为DBNull.Value
,Convert.ToInt32
将InvalidCastException
扼杀 if (!DBNull.Value.Equals(_row.Row["RegWaitTime"]))
{
//then do the conversion as you are doing now.
}
因为对象不能从DBNull转换为其他类型。
另一种选择是:
{{1}}
答案 1 :(得分:0)
检查数据库NULL,如下所示:
if(_row.Row["RegWaitTime"] != DBNull.Value)
{
//change colour
{
else
{
//do what you need to do when you get a NULL value
}