我得到Exception为System.IndexOutOfRangeException /或此位置没有行 [英] i am getting Exception as System.IndexOutOfRangeException/ or no rows at this position
本文介绍了我得到Exception为System.IndexOutOfRangeException /或此位置没有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
at line drr = dt.Rows [i]
at line drr = dt.Rows[i]
if this happening i want to move on next row of table and if row is there that row's value should display
//代码是
//code is
public partial class WebForm9 : System.Web.UI.Page
{
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
DataRow drr;
public string ans_tea;
public string ans_stu;
SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=swatidb;Integrated Security=True;Pooling=False");
static int i = 0;
public void Page_Load(object sender, EventArgs e)
{
con.Open();
string tea_id = TextBox2.Text;
string s1 = "select student_id from Student where user_name='" + Session["sid"] + "'";
SqlCommand cmd = new SqlCommand(s1, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label4.Text = dr[0].ToString();
dr.Close();
}
}
public void Button2_Click(object sender, System.EventArgs e)
{
string tea_id = TextBox2.Text;
cmd = new SqlCommand("SELECT * from Question WHERE Teacher_id=@tea_id", con);
cmd.Parameters.AddWithValue("@tea_id", tea_id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);//at this line getting Exception so how can i avoid getting this Exception
drr = dt.Rows[i];
if (i == (dt.Rows.Count - 1))
{
Response.Write("Last record !");
}
else
{
i++;
}
Label3.Text = Convert.ToString(drr[0]);//for displaying question_id
Label2.Text = Convert.ToString(drr[2]);//for displaying question
con.Close();
}
推荐答案
你应该像这样修改你的代码行:
You should modify your line of code code like this:
if (i >= dt.Rows.Count))
{
Response.Write("There are no record !");
con.Close();
return;
}
drr = dt.Rows[i];
//... your old code!
static int i = 0;
为什么你那样做吗?问题的原因可能在于:你假设i的某个值因为同时处理你的类的另一个实例或者在不同的函数中被更改而不再有效。除了Paul的回答你也可以更好地修复它。
static int i = 0;
Why do you do that? The cause of the problem is likely based here: you assume some value for i which is no more valid due to another instance of your class being processed at the same time or i being changed in a different function etc. In addition to Paul's answer you'd better repair that too.
这篇关于我得到Exception为System.IndexOutOfRangeException /或此位置没有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文