有時我們從數據庫中獲取我們想要的數據時,難免會遇到取出的數據為空( C#中用DBNull這種類型表示)的情況,如果直接使用強制轉換,則會拋出異常。
例如:

String strSQL = string.Format("select SUM(point) from video_userconsume where userid=''{0}'' and roomsession={1} and state=3 ", Session["userid"], roomsession);

decimal giFTPoints = (decimal)SqlHelper.ExecuteScalar(BasePage.GetConnectString(), CommandType.Text, strSQL);
正確的處理方法如下:

String strSQL = string.Format("select SUM(point) from video_userconsume where userid=''{0}'' and roomsession={1} and state=3 ", Session["userid"], roomsession);


Object o = SqlHelper.ExecuteScalar(BasePage.GetConnectString(), CommandType.Text, strSQL);
decimal giFTPoints =0;
//使用is 關鍵字判斷取出的對象是否為DBNull類型

if (o is DBNull)

giFTPoints
=0;
else

giFTPoints
= (decimal)o;