簡體   English   中英

超出范圍的數據集異常

[英]Out of range exception of a dataset

希望這是一個簡單的

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

如果我點擊我的數據網格中的第一個結果........將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();

添加一項檢查以確保您的查詢至少檢索了一行

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集合具有零元素,您無法訪問索引零。 (超出范圍)

我會猜測問題是你傳遞了錯誤的id,或者cds表中沒有傳遞id的數據。

當您嘗試訪問Rows[0] ,由於沒有數據,您會收到錯誤,因此集合中沒有行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM