对不起,我还是C#n00b。我有这个代码将从我的控件中检索项目。问题是,最终的SQL字符串有点偏。我的s2变量中有一个额外的逗号。
这是我的代码隐藏:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
//String with all selected items in ListBox lstFilter
var selectedQuery = lstFilter.Items.Cast<ListItem>().Where(item => item.Selected);
string txtlstFilter = String.Join("','", selectedQuery).TrimEnd();
//String with all selected items in CheckBoxList cbFields1
string s1 = string.Empty;
new List<ListItem>(cbFields1.Items.Cast<ListItem>().Where(i => i.Selected)).ForEach(x => s1 += string.Format("{0}, ", x.Value));
//String with all selected items in CheckBoxList cbFields2
string s2 = string.Empty;
new List<ListItem>(cbFields2.Items.Cast<ListItem>().Where(j => j.Selected)).ForEach(y => s2 += string.Format("{0}, ", y.Value));
// textBox1.Text = s;
var strSQL = "SELECT " + s1 + s2 + " FROM vwClaimRoster WHERE " + cboFilterOption.SelectedValue + " in ('" + txtlstFilter + "');";
}
这就是strSQL最终的结果(基于我选择的内容):
“SELECT MgrName,Division,Routing,Dept,ExpCtr,State,EEName,Argus,CCP,ChkRework,FROM vwClaimRoster WHERE Dept in('ACCOUNT ADVOCACY','BILLING CONTROL','CCF CLAIM');” p>
正如你所看到的,我需要摆脱我的字段列表中的最后一个逗号(ChkRework之后的那个逗号)。
任何帮助将不胜感激!
答案 0 :(得分:1)
对于第一部分,使用Union
加入ListItems,然后使用string.Join
获取以逗号分隔的列表(而不是ForEach
):
string selectList = string.Join(", ",
cbFields1.Items.Cast<ListItem>()
.Union(cbFields2.Items.Cast<ListItem>())
.Where(i => i.Selected)
.Select(x => x.Value)
);
对于第二部分,只需将单引号添加到string.Join
,以及之前/之后:
string strSQL = "SELECT " + selectList + " FROM vwClaimRoster WHERE " + cboFilterOption.SelectedValue
" in ('" + String.Join("','", selectedQuery).TrimEnd() + "');";
^ ^ ^ ^