編輯:因爲WHERE
條款也依賴於檢查checkBoxes
,我已經編輯我的答案和擴大Dictionary
以包括where
子句值。請記住,這是通用解決方案,更適合作爲提示使用,而不是真正的解決方案。
首先,不要使用命令文本字符串連接並瞭解參數化查詢。 關於你的問題,我會建議Dictionary
的做法。 使用您的CheckBox
名稱作爲鍵和Tuple包含列名稱和文本框作爲值作爲字典。
因此,定義字典是這樣的:
Dictionary<string, Tuple<string, string>> dict = new Dictionary<string, Tuple<string, string>();
使用值填充它:
dict.Add(checkBox1.Name, new Tuple<string, string>("regnr", TextBox1.Text));
dict.Add(checkBox2.Name, new Tuple<string, string>("benamning", TextBox2.Text));
dict.Add(checkBox3.Name, new Tuple<string, string>("dimension", TextBox3.Text));
//etc..
在你的形式,像這樣得到選中的複選框的名字:
var checkedCheckBoxes = this.Controls.OfType<CheckBox>().Where(cb => cb.Checked).Select(cb => cb.Name);
現在,從您的字典中找到匹配的列。從該列表中爲select
和where
子句創建列名稱。
List<Tuple<string, string>> columnNames = dict.Where(pair => checkedCheckBoxes.Contains(pair.Key)).Select(pair => pair.Value).ToList();
string selectColumnNames = string.Join(", ", columnNames.Select(t => t.Item1).ToArray());
string whereClause = "";
for (int i = 0; i < columnNames.Count(); i++)
{
if (i > 0) whereClause +=" and ";
whereClause += string.Format("{0} = @{0}", columnNames[i]);
}
最後,用這個命令生成文本。
string commandText = string.Format("SELECT {0} FROM erkstad.dackforvaring WHERE {1}", selectColumnNames, whereClause);
和從Tuple.Item2
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = commandText;
foreach (var columnName in columnNames)
{
cmd.Parameters.AddWithValue(("@" + columnName.Item1), columnName.Item2);
}
var reader = cmd.ExecuteReader();
https://en.wikipedia.org/wiki/SQL_injection – Jamiec
WHST是'regnr','benamning'執行參數的SqlCommand,傳遞參數值?正如目前所寫,很難確切地說出你在問什麼。請參閱[如何提問](http://stackoverflow.com/help/how-to-ask)頁面以獲得澄清此問題的幫助。 – Marusyk
您希望列成爲搜索條件的一部分嗎?像'在哪裏regnr像'添加%'和像'dfds%'一樣的變形?或者他們應該只是選擇列列表的一部分? –