0

在此处输入图像描述

每当我想在我的航空公司预订系统项目中预订航班时,我都会在上图中出现此错误,我的代码中出现异常错误,此错误消息正在弹出

IndexOutOfRangeException unhandles by user code

...关于我如何去做的任何想法我的代码是使用 c sharp 在 asp.net 中编写的?

这是代码

public partial class TICKET_BOOKING : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    int a;
    String constring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString.ToString();
    public int Autonumber()
    {
        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; //this is where its occuring
        con.Close();
        return a;
    }
4

2 回答 2

2

试试这个

    int a;
    String constring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString.ToString();
    public int Autonumber()
    {
        using (SqlConnection con = new SqlConnection(constring))
        {
            SqlCommand cmd = new SqlCommand
                                 {
                                     CommandType = CommandType.Text,
                                     Connection = con,
                                     CommandText = "select pid from pid",
                                 };
            con.Open();
            // cmd.Connection.Open();
            using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                        a = reader.GetInt32(0);
                }
            }
            return a;
        }
    }
于 2012-10-25T07:44:32.527 回答
0

您的数据表中没有记录,所以接下来

dt.Rows[0][0]

失败。请在加入之前检查表是否有记录。像这样的东西:

if(dt.Rows.Count > 0) 
{ 
   a = Convert.ToInt32(dt.Rows[0][0].ToString()) + 1; 
}
于 2012-10-25T07:35:30.130 回答