[英]How to load information from database to a Label in Asp.Net?
当用户单击上一页中的链接按钮时,我想从数据库中的特定列加载数据。
我正在使用SqlDataReader
来执行此操作,但出现错误:
指数数组的边界之外。
这是我的代码:
private void loadDetails()
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand cmd = new SqlCommand("select expectation from Tours where tourName ='" + tournameLb.Text + "'", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@expectation", lb5.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lb5.Text = dr[4].ToString(); //I get error here
}
dr.Close();
con.Close();
}
在哪里
tournameLb.Text = Session["tourName"].ToString();
您正在使用该值的参数,这是一个好方法,但您需要使用参数化查询:
SqlCommand cmd = new SqlCommand("select expectation from Tours where tourName = @expectation", con);
此外,您的查询只会返回一列,但您正在尝试获取不存在的第五列的值:
lb5.Text = dr[0].ToString();
或者,您可以使用列名而不是索引:
lb5.Text = dr["expectation"].ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.