retrieving data from sql database using C# with stored procedure
You need to call Read
before you can access data, Your code should be
While (dr.Read())
{
Label1.Text = dr["FirstName"].ToString();
Label2.Text = dr["LastName"].ToString();
Label3.Text = dr[3].ToString();
Label4.Text = dr["Email"].ToString();
}
//close DataReader
dr.Close();
Before you read column values from DataReader you must invoke Read() method from data reader.
if (dr.Read())
{
Label1.Text = dr["FirstName"].ToString();
Label2.Text = dr["LastName"].ToString();
Label3.Text = dr[3].ToString();
Label4.Text = dr["Email"].ToString();
}
You can also try:
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
You are missing a call to Read()
on your reader. I also suggest you wrap your IDisposable
objects in using
statements as below.
You also seem to be using a strange combination of column names and ordinal positions when retrieving your values from the SqlDataReader
.
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection myConnection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection))
{
cmd.CommandType = CommandType.StoredProcedure;
myConnection.Open();
SqlParameter custId = cmd.Parameters.AddWithValue("@CustomerId", 10);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
Label1.Text = dr["FirstName"].ToString();
Label2.Text = dr["LastName"].ToString();
Label3.Text = dr[3].ToString();
Label4.Text = dr["Email"].ToString();
}
}
}
}
}