[英]How to load information from database to a Label in Asp.Net?
I would like to load a data from a specific column in the database when a user clicks on a link button from the previous page.当用户单击上一页中的链接按钮时,我想从数据库中的特定列加载数据。
I am using the SqlDataReader
to do this, but I get the error:我正在使用SqlDataReader
来执行此操作,但出现错误:
Index was outside the bounds of the array.指数数组的边界之外。
Here is my code:这是我的代码:
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();
}
Where在哪里
tournameLb.Text = Session["tourName"].ToString();
You're using a parameter for the value, which is the good way, but you need to use a parameterized query with it:您正在使用该值的参数,这是一个好方法,但您需要使用参数化查询:
SqlCommand cmd = new SqlCommand("select expectation from Tours where tourName = @expectation", con);
Also your query will only return one columns, but you're trying to get the value of the fifth column which doesn't exist:此外,您的查询只会返回一列,但您正在尝试获取不存在的第五列的值:
lb5.Text = dr[0].ToString();
Alternatively, you can use the name of the column instead of the index:或者,您可以使用列名而不是索引:
lb5.Text = dr["expectation"].ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.