0
Hi Samir,
Please see code below.
If you'll notice, I added a parameter even before initializing the command text. Validation of command text and parameters will only happen during ExecuteReader(). Same principle applies with your issue. You can add as many parameters as you would like even with the wrong commandtext and your application wouldn't even complain, until you execute ExecuteReader().
static void Test1()
{
SqlConnection sqlConnection = new SqlConnection("Data Source=ce00959dc;Initial Catalog=northwind;User Id=samir;Password=samir;");
SqlCommand sqlCommand = new SqlCommand();
SqlDataReader sqlDataReader = null;
System.Data.SqlClient.SqlParameter sqlParameter = sqlCommand.CreateParameter();
sqlParameter.ParameterName = "CategoryName";
sqlParameter.Value = "Beverages";
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.Parameters.Add(sqlParameter);
sqlCommand.CommandText = "SELECT * FROM Categories WHERE CategoryName=@CategoryName";
sqlConnection.Open();
sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
Console.WriteLine("Category = " + (string)sqlDataReader["CategoryName"]);
}
sqlConnection.Close();
}

0
I tried it, and i don't think it will work because you have to define the parameter in the SqlCommand command string before you can add the parameter...
0
You will only need the if conditions in constructing your sSQL. At the same time, you could already add the specific parameter for each sSQL condition. AFAICR, this is OK although you're not yet finished constructing your sql statement. No need to do another set of if conditions just to assign the parameter.
Please see this link for info on how to use sqlparameters ->
Goodluck.