Initialize Connection error

  • Thread starter Thread starter RP
  • Start date Start date
R

RP

When I execute following code, this error is displayed :

ExecuteReader: Connection property has not been initialized, on line
4.

------------------------------------------------------------------------------------------
1 OpenConnection();
//Get Allowance Records
2 string qAllow = "Select ADCode from ADMaster where
ADType='A'";

3 SqlCommand AllCmd = new SqlCommand(qAllow, CN);

4 SqlDataReader dr = AllCmd.ExecuteReader();
-----------------------------------------------------------------------------------------
 
When I execute following code, this error is displayed :

ExecuteReader: Connection property has not been initialized, on line
4.

---------------------------------------------------------------------------­---------------
1 OpenConnection();
//Get Allowance Records
2 string qAllow = "Select ADCode from ADMaster where
ADType='A'";

3 SqlCommand AllCmd = new SqlCommand(qAllow, CN);

4 SqlDataReader dr = AllCmd.ExecuteReader();
---------------------------------------------------------------------------­--------------


What does the OpenConnection() sub do?
 
That problem got resolved by:

Public SQLConnection CN = new SQLConnection();

Previously I was just doing:

Public SQLConnection CN;

Now the next problem is here:

=======================================
//Get Allowance Records
string qAllow = "Select ADCode from ADMaster where
ADType='A'";

SqlCommand AllCmd = new SqlCommand(qAllow, CN);
SqlDataReader dr;
dr = AllCmd.ExecuteReader();
string qNew = "";

while (dr.Read()== true)
{
qNew = "ALTER TABLE NewT ADD " + dr[0].ToString() + "
varchar(12)";
SqlCommand Ins2 = new SqlCommand(qNew,CN);
Ins2.ExecuteNonQuery();
Ins2.Dispose();
}
dr.Close();
==================================

At line Ins2.ExecuteNonQuery.

Error: There is already an open DataReader associated with this
Command which must be closed first.
 
That problem got resolved by:

Public SQLConnection CN = new SQLConnection();

Previously I was just doing:

Public SQLConnection CN;

Now the next problem is here:

=======================================
//Get Allowance Records
string qAllow = "Select ADCode from ADMaster where
ADType='A'";

SqlCommand AllCmd = new SqlCommand(qAllow, CN);
SqlDataReader dr;
dr = AllCmd.ExecuteReader();
string qNew = "";

while (dr.Read()== true)
{
qNew = "ALTER TABLE NewT ADD " + dr[0].ToString() + "
varchar(12)";
SqlCommand Ins2 = new SqlCommand(qNew,CN);
Ins2.ExecuteNonQuery();
Ins2.Dispose();
}
dr.Close();
==================================

At line Ins2.ExecuteNonQuery.

Error: There is already an open DataReader associated with this
Command which must be closed first.

You cannot execute a nonquery on a connection that has a dataread
still open, just as the exception message says. If you want to execute
a nonquery while reading a datareader, you will need a second
connection. That's just how it works.
 
Back
Top