2012-03-11 103 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