Reputation: 127
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:
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();
Upvotes: 1
Views: 758
Reputation: 25351
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();
Upvotes: 1