Sunday, March 28, 2010

ExecuteReader: Connection property has not been initialized

This is common error if you don't set connection property of the command object.

Suppose that you have code something like this:

SqlConnection con = new SqlConnection(myConnectionString);
SqlCommand cmd = new SqlCommand("SQL STATEMENT");


well, in this peace of code your command object doesn't know anything about your connection. To fix this create your command object like this:

SqlCommand cmd = new SqlCommand("SQL STATEMENT", con);

or if you use empty constructor or don't set connection property in costructor assign connection as property:

cmd.Connection = con;