0

我在 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");
            }
        }




     }
4

2 回答 2

0

您需要将转换代码更改为:

int field=0;

if(int.TryParse(_row.Row["RegWaitTime"],out field))
{
    if(field>30)
    {
    }
}

你需要这个的原因是 if _row.Row["RegWaitTime"]is NULL,你会得到的实际值是抛出一个因为对象不能从 DBNull 转换为其他类型DBNull.Value而窒息。Convert.ToInt32InvalidCastException

另一种选择是:

 if (!DBNull.Value.Equals(_row.Row["RegWaitTime"]))
 {
    //then do the conversion as you are doing now. 
 }
于 2012-05-23T03:17:13.010 回答
0

检查数据库 NULL,如下所示:

if(_row.Row["RegWaitTime"] != DBNull.Value)
{
    //change colour
{
else
{
    //do what you need to do when you get a NULL value
}    
于 2012-05-23T03:22:28.170 回答