2010-06-14 65 views
1

我使用在其表的簡歷和列的PageIndex數據庫,類型是數據庫數字,不過,我想這PageIndex的值存儲爲一個整數,我得到異常錯誤容納張數

指定的轉換無效。

這裏是代碼

string sql; 
string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Deliverable4.accdb"; 
protected OleDbConnection rMSConnection; 
protected OleDbDataAdapter rMSDataAdapter; 
protected DataSet dataSet; 
protected DataTable dataTable; 
protected DataRow dataRow; 

上按鈕點擊

sql = "select PageIndex from RESUME"; 
rMSConnection = new OleDbConnection(conString); 
rMSDataAdapter = new OleDbDataAdapter(sql, rMSConnection); 
dataSet = new DataSet("pInDex"); 
rMSDataAdapter.Fill(dataSet, "RESUME"); 

dataTable = dataSet.Tables["RESUME"]; 

INT p食指= (INT)dataTable.Rows [0] [0];

rMSConnection.Close(); 

if (pIndex == 0) 
{    
    Response.Redirect("Create Resume-1.aspx"); 
} 
else if (pIndex == 1) 
{    
    Response.Redirect("Create Resume-2.aspx"); 
} 
else if (pIndex == 2) 
{   
     Response.Redirect("Create Resume-3.aspx"); 
    } 
} 

我得到這一行

int pIndex = (int)dataTable.Rows[0][0]; 

回答

0

我可以很謙恭地建議這樣做的不同的方式?:

string conString = "..."; // <-- your connection string 

using (IDbConnection connection = new OleDbConnection(conString)) 
{ // ^^^ interface type makes your code less dependent on a particular backend! 
    connection.Open(); 
    try 
    { 
     using (IDbCommand command = connection.CreateCommand()) 
     { // ^^^ ditto 
      command.CommandText = "SELECT PageIndex FROM RESUME"; 
      object scalar = command.ExecuteScalar(); 
      //^ExecuteScalar reads the first value in the first column 
      // of the result set; or returns null if it fails to do so. 

      if (scalar == null) throw ...; // unexpected result from database! 
      if (scalar == DBNull.Value) throw ...; // ditto!? 

      int pIndex = (int)scalar; 

      switch (pIndex) 
      { 
       case 0: Response.Redirect("Create Resume-1.aspx"); break; 
       case 1: Response.Redirect("Create Resume-2.aspx"); break; 
       case 2: Response.Redirect("Create Resume-3.aspx"); break; 
       default: throw ...; // unexpected result from database!? 
      } 
     } 
    } 
    finally 
    { 
     connection.Close(); // (will execute even when exceptions are thrown!) 
    } 
} 
+0

空數據庫值會產生'DBNull.Value',不'null'。 – 2010-06-14 18:35:33

+0

* @ Adam Robinson:*正確(我加了這個例子),但是請注意,如果*不是第一行的第一列,那麼仍然可以發生'null',即。當返回的結果集完全爲空時。 – stakx 2010-06-14 18:36:32

2

如果無法將其轉換爲整數的錯誤,那麼就不會檢索它作爲一個從數據庫中。該字段的數據類型是什麼?

嘗試檢查dataTable.Rows[0][0].GetType().ToString()的結果以查看對象實際是什麼。

2

你說「類型數據庫數」 - 這聽起來,雖然這可能是numeric,在這種情況下,.NET的土地最合適的匹配是decimal。如果你知道它是一個int,你可以簡單地從decimalint事後投它:

int pIndex = (int)(decimal)dataTable.Rows[0][0]; 
0

我解決了這個問題。

int pIndex = int.Parse(dataTable.Rows[0][0].ToString());