本文介绍了我得到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();
}
推荐答案
if (i >= dt.Rows.Count))
{
Response.Write("There are no record !");
con.Close();
return;
}
drr = dt.Rows[i];
//... your old code!
这篇关于我得到Exception为System.IndexOutOfRangeException /或此位置没有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!