2012-03-11 93 views
0

,同時試圖連接到我已經在我的網頁加載方法寫了下面的代碼數據庫:指數超出範圍的異常

SqlConnection con = new SqlConnection(constring); 
    SqlCommand cmd = new SqlCommand(); 
    cmd.CommandType = CommandType.Text; 
    cmd.Connection = con; 
    con.Open(); 
    cmd.CommandText = "select pid from pid"; 
    SqlDataAdapter da = new SqlDataAdapter(); 
    DataSet ds = new DataSet(); 
    DataTable dt = new DataTable(); 
    da.SelectCommand = cmd; 
    da.Fill(dt); 
    a = Convert.ToInt32(dt.Rows[0][0].ToString()) + 1; 
    con.Close(); 
    return a; 

和IM得到一個錯誤的代碼行「A = Convert.ToInt32(dt.Rows [0] [0]的ToString())+ 1;「爲: 索引超出範圍異常 沒有排在位置0 如何繼續?

回答

0

推測,您的查詢沒有返回任何行。相應地進行處理(如果查詢可能不返回任何行,請添加if語句)。否則,你的查詢可能有些問題(從同名對象中選擇一個列似乎不正確)。

int retVal = default(int); 

if(dt.Rows.Count == 1) 
{ 
    retVal = (int)dt.Rows[0][columnName]; 
} 

return retVal; 
+0

cmd.CommandText = 「插入的plist(PID,passengername,FLIGHTID,Flightname,Fromstation,Tostation,類別,Dateandtimings)值('」 +自動編號()+ 「 ''」 + TextBox1.Text + 「','」+ DropDownList1.Text +「','」+ DropDownList2.Text +「','」+ DropDownList3.Text +「','」+ DropDownList4.Text +「','」+ DropDownList5.Text + 「','」+ DropDownList6.Text +「')」; int i = cmd.ExecuteNonQuery(); 錯誤消息: System.Data.SqlClient.SqlException:不能在表「的plist」當IDENTITY_INSERT設置爲OFF時插入用於標識列顯式值。 – user1240912 2012-03-11 08:53:59

+0

這意味着您不能在您的標識列中插入顯式值。您的插入語句可能是錯誤的。 – 2012-03-11 09:01:43