First part: there is a much simpler way:
string qamm = "Guide,Transport";
var list = new List<string>(qamm.Split(','));
Only two lines, and the
Split()
method is called only once.
As a general rule, you don't want to call this kind of method in a loop when you can do it only once and store its result in a variable.
Second part: I'm having trouble to see what you want to get here. The content of the datatable will be replaced by each subsequent call to
Fill
. Moreover, you must not build SQL queries by concatenating strings, because you leave your application open to SQL injection attacks. Better used parametrized queries instead. You should also avoid
SELECT *
as much as possible, but rather clearly specify the columns which you want. Also, you should give you variables some meaningful names, and stay consistent with the casing of method names. You should also use disposable objects (connections, commands) in
using
blocks, to properly free resource intensive objects when you don't need them anymore.
d123.CONNECTER();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = d123.con;
var builder = new StringBuilder("SELECT * FROM whats_included WHERE Title_of_whats_in IN (");
for (int i = 0; i < list.Count; ++i)
{
builder.Append($"@cat{i},");
}
builder.Remove(builder.Length - 1, 1);
builder.Append(")");
cmd.CommandText = builder.ToString();
for (int i = 0; i < list.Count; ++i)
{
cmd.Parameters.Add($"@cat{i}", SqlDbType.NVarChar).Value = list[i];
}
d123.dap = new SqlDataAdapter(cmd);
d123.dap.Fill(d123.dt);
}
d123.DECONNECTER();
This code should fill your table with rows filtered by the values in the original
qamm
string.