Mike Eghtebas
asked on
ExecuteReader: Connection property has not been initialized. asp.net c#
I am getting: "ExecuteReader: Connection property has not been initialized." at line 19 (SqlDataReader rdr = cmd.ExecuteReader();).
Question: How can I handle this error?
This is a asp tutorial I am duplicating.
Question: How can I handle this error?
This is a asp tutorial I am duplicating.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["StudentDB"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Select ID, FirstName, LastName, Gender FROM Students WHERE Gender='Male'");
List<Student> listStudents = new List<Student>();
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Student student = new Student();
student.ID = Convert.ToInt32(rdr["ID"]);
student.FirstName = rdr["FirstName"].ToString();
student.LastName = rdr["LastName"].ToString();
student.Gender = rdr["Gender"].ToString();
listStudents.Add(student);
}
con.Close();
GridView1.DataSource = listStudents;
GridView1.DataBind();
}
}
-------------------------
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
Data Source=USER-PC;Initial Catalog=ROD_July18;Integrated Security=True
Data Source=.\SQLEXPRESS12;Initial Catalog=MME_Sample; Integrated Security=True
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="StudentDB" connectionString="Data Source=.\SQLEXPRESS12;Initial Catalog=MME_Sample; Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I meant line 16, and be sure to move line 18 before 16 (open the connection before creating the command)
ASKER
Eric,
FYI "be sure to move line 18 before 16" is not necessary.
Mike
FYI "be sure to move line 18 before 16" is not necessary.
Mike