Link to home
Start Free TrialLog in
Avatar of dpicco
dpiccoFlag for United States of America

asked on

how to read fields from a data reader

Hello experts,
Can anyone tell me what I'm doing wrong with this data reader? I'm getting a result back when I query the database directly. Browser error is Invalid attempt to read when no data is present.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) 
        {
            Session["uid"] = Request.QueryString["uid"];

            SqlCommand command;
            SqlConnection conn;
            SqlDataReader dr = null;

            string sqlString = @" SELECT first_name + ' ' + last_name full_name FROM people WHERE network_account = @network_account";

            using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AdHocReportingConnectionString"].ConnectionString.ToString()))
            {
                using (command = conn.CreateCommand())
                {
                    conn.Open();
                    command.CommandText = sqlString;
                    command.CommandType = CommandType.Text;
                    command.Parameters.AddWithValue("@network_account", Session["uid"].ToString());

                    using (dr = command.ExecuteReader(CommandBehavior.SingleResult))
                    {
                        if (dr.HasRows)
                        {
                            Session["FullName"] = dr["full_name"].ToString();
                        }
                    }
                }
            }
        }

        this.Label1.Text = Session["FullName"].ToString();
     }

Open in new window

Avatar of Gary Davis
Gary Davis
Flag of United States of America image

After the ExecuteReader, dr has the value, not the row since you are using SingleResult.

Gary Davis
Also, don't use the "using" in this case and also you will not be getting back a datareader.
ASKER CERTIFIED SOLUTION
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dpicco

ASKER

Thanks.