I have several comboboxes and I would like to check those that are checked to retrieve their values and use them in a sql query.
I tried to put all the checkboxes in a flowLayoutPanel and use a foreach to retrieve their contents.I think it’s a syntax problem in my sql query.
List<string> selection = new List<string>();
foreach (CheckBox cb in flowLayoutPanel1.Controls)
{
if (cb.Checked)
selection.Add(cb.Text);
}
SqlCommand command = new SqlCommand("SELECT JOB_HEADER.P FROM JOB_HEADER WHERE JOB_HEADER.MODE_F = selection")
Here is the mistake I get : An unhandled exception of type ‘System.Data.SqlClient.SqlException’ occurred in System.Data.dll
Additional information: Invalid column name ‘selection’.
Sorry if the solution is obvious I am a beginner. Thanks for your help.
Advertisement
Answer
Your actual error is caused by the word selection. This is not the list variable but a literal text inside a string and the database engine has no way to know how to extract the list values from that word. So it thinks that you have written a column name and it cannot find it.
The solution is more complex than you think.
You need a collection of parameters and a collection of names to put inside an IN clause
int pcount = 1;
// This is where we keep the placeholder text for the parameters
List<string> names = new List<string>();
// This is the list of parameters built using the checkboxes checked state
List<SqlParameter> prms = new List<SqlParameter>();
foreach (CheckBox cb in flowLayoutPanel1.Controls)
{
if (cb.Checked)
{
names.Add("@p" + pcount);
prms.Add(new SqlParameter
{
ParameterName = "@p" + pcount,
SqlDbType = SqlDbType.NVarChar,
Value = cb.Text,
// For performance it would be useful also to specify the column size
// Size = 100,
});
pcount++;
}
}
// Build the sql command adding all the parameters placeholders inside an IN clause
string cmdText = @"SELECT JOB_HEADER.P FROM JOB_HEADER WHERE JOB_HEADER.MODE_F IN(";
cmdText += string.Join(",", names) + ")";
SqlCommand command = new SqlCommand(cmdText, connection);
// Give the parameters collection to the command
command.Parameters.AddRange(prms.ToArray());