0

asp.net 3.5 Web ページに GridView コントロールがあり、RowDataBound イベントで次のコードが実行され、列の値が RegWaitTime で、TotalWegTime が 30 を超えると、背景色とフォント色が変更されます。

値は、他の 2 つの列からの減算の結果を返す SQL サーバーの 2 つの計算列から取得されます。ここでの問題は、これらの列の値が 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)
    {
    }
}

これが必要な理由は、 _row.Row["RegWaitTime"]isの場合、オブジェクトを DBNull から他の型にキャストできないためNULL、実際に取得される値はDBNull.ValueConvert.ToInt32スローすると詰まるからです。InvalidCastException

別の代替手段は次のとおりです。

 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 に答える