Before you dowonvote this, please have a look first. I know there numerous threads here with this errormessage, but I haven't found one with this particular problem. I've created a custom command class implementing the IDbCommand interface like this:
internal class Prozedur : IDbCommand
{
private static SqlCommand command = new SqlCommand() ;
private SqlConnection connection;
string commandtext;
CommandType commandType;
public Prozedur(string abfrage)
{
commandtext = abfrage;
commandType = CommandType.StoredProcedure;
connection = (SqlConnection)new Verbindung();
SqlCommand command = new SqlCommand(commandtext, connection);
}
public static explicit operator SqlCommand(Prozedur v)
{
return command;
}
...
I'am using the object like this:
internal class Tabelle : DataTable
{
DataTable tabelle = new DataTable();
internal Tabelle(string abfrage)
{
Prozedur p = new Prozedur(abfrage);
SqlDataAdapter adapter = new SqlDataAdapter((SqlCommand)p);
adapter.Fill(tabelle);
}
}
However, on the adapter.Fill(tabelle)
i get the Error “Fill: SelectCommand.Connection property has not been initialized.”. But if i look at the object p, the connection is there:
Update
If i change the code like this
internal class Tabelle : DataTable
{
DataTable tabelle = new DataTable();
internal Tabelle(string abfrage)
{
Prozedur p = new Prozedur(abfrage);
SqlCommand c = (SqlCommand)p;
//added this line
c.Connection = p.Connection;
SqlDataAdapter adapter = new SqlDataAdapter((SqlCommand)p);
adapter.Fill(tabelle);
}
}
I get a compiler error for p.Connection;
C# Cannot implicitly convert type to. An explicit conversion exists (are you missing a cast?).
The code for the connection is this:
public IDbConnection Connection
{
get
{
return connection;
}
set
{
connection = (SqlConnection)value;
}
}
The problem was in the convert method. When I change the code as below it works. Basically I had to make all variables static and return a new
SqlCommand
Object in the convert method.And it works like this without static variables: