2013-03-19 98 views
0

希望這是一個簡單的超出範圍的數據集例外

我正在從我的數據集的一列中提取數據。由於提供了SQL查詢,一個ID只會返回一個結果。所以我會認爲這個結果總是在數據集的'0'行。

如果我點擊我的datagrid中的第一個結果........發送ID'0'到我的第二頁,然後從數據庫中提取圖像名稱它崩潰。如果我在網格中選擇第二個結果(即'1'),那很好。

這裏是我的代碼:

 SqlConnection sqlcon = new SqlConnection(connstring); 
     SqlCommand sqlcmd = new SqlCommand("select pic from cds WHERE _id = '" + passedID + "'", sqlcon); 
     SqlDataAdapter adp = new SqlDataAdapter(sqlcmd); 
     DataSet ds = new DataSet(); 
     adp.Fill(ds); 
     // Rows set to '0' for the first result in the dataset but crashes if the first item is selected. 
     object a = ds.Tables[0].Rows[0]["pic"]; 
     string test = a.ToString(); 

回答

2

添加檢查,以確保您的查詢檢索已至少一行

if(ds.Tables[0].Rows.Count > 0) 
{ 
    object a = ds.Tables[0].Rows[0]["pic"]; 
    string test = a.ToString(); 
} 
else 
{ 
    Response.Write("No rows for the ID = " + passedID); 
} 

數據集沒有行。它是包含在具有Rows屬性的數據集中的DataTable,但如果您的查詢失敗(未找到具有所請求的ID的行),則Rows集合中的元素爲零,並且您無法訪問索引零。 (超出範圍)

0

我會猜測問題是您要麼傳遞錯誤的ID,要麼傳入的ID的cds表中沒有數據。

當您嘗試訪問Rows[0]時,由於沒有數據而出現錯誤,因此集合中沒有行。