I currently have a connection class that handles all of my database connectivity. What I am trying to do is build a SqlParameterCollection object on one page, then pass that object to my connection class. Is it possible to do this? I am not getting any compilation errors, but I can not get the parameters to be recognized. Here is what I am trying to do:
Page 1:
string sql = null;
conn.strConn = connectionstring;
sql = "sqlstring";
SqlParameterCollection newcollect = null;
newcollect.Add("@Switch",1);
conn.OpenReader(sql, newcollect);
while (conn.DR.Read())
{
read data onto page here...
}
conn.CloseReader();
Page 2 (connection class) :
public void OpenReader(string sql, SqlParameterCollection collect)
{
Conn = new SqlConnection(strConn);
Conn.Open();
Command = new SqlCommand(sql,Conn);
Command.Parameters.Add(collect); <------This is the root of my question
Command.CommandTimeout = 300;
// executes sql and fills data reader with data
DR = Command.ExecuteReader();
}
Basically, in ASP.NET, to persist something from page to page, you need to use session state and put your object there - so you could try something like this:
Page 1:
List<SqlParameter> newcollect = new List<SqlParameter>();
newcollect.Add(new SqlParameter("@Switch", 1));
Session["SqlParameters"] = newcollect;
Page 2 (connection class) :
public void OpenReader(string sql)
{
Conn = new SqlConnection(strConn);
Conn.Open();
Command = new SqlCommand(sql,Conn);
List<SqlParameter> coll = null;
if(Session["SqlParameters"] != null)
{
coll = (List<SqlParameter>)Session["SqlParameters"];
}
Command.Parameters.AddRange(coll.ToArray());
Command.CommandTimeout = 300;
// executes sql and fills data reader with data
DR = Command.ExecuteReader();
}
This will work - if you have Session state enabled on your ASP.NET site. This will not work if your site cannot use session state memory for some reason (like if you're on a webfarm and cannot use SQL Server for session state)