我在上面的图片中出现此错误每当我想在我的航空公司预订系统项目中预订航班时,我的代码中出现异常错误此错误消息正在弹出
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;
}
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
您的数据中没有记录,所以下一步
dt.Rows[0][0]
失败。请在加入之前检查表格是否有记录。这样的事情:
if(dt.Rows.Count > 0)
{
a = Convert.ToInt32(dt.Rows[0][0].ToString()) + 1;
}