Dallas Walker Dallas Walker - 8 days ago 6
ASP.NET (C#) Question

SqlDataReader not executing correctly in asp.net page using C#

I've hit the database in another section of my code using

SqlDataAdapter
but I just need a reader to return one row for me and this code isn't working right. Can someone see where I'm making a mistake?

I'm just trying to assign one label a value from the first column of my row returned. I can't get either alert to pop when its ran either below.

private void loadProcInfo(string procid)
{
try
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
SqlCommand query = new SqlCommand("SELECT * FROM dbo.Book1 WHERE ID ='" + procid +"'", con);

//ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('"+query+"');", true);

using (SqlDataReader procinfoload = query.ExecuteReader())
{
if (procinfoload.Read())
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('IT WORKED');", true);
Id.Text = procinfoload.GetValue(0).ToString();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('not success!');", true);
}
}

con.Close();
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex + "');", true);
//MessageBox.Show(ex.Message);
}
}

Answer

Open the connection before attempting to execute the reader.

con.Open();