数据表使用' IN'选择行第C#.net条款

时间:2017-12-28 20:36:28

标签: c# .net

string selectedLeaveTypes = "";
  foreach (ListItem item in chkLeaveType.Items)
      {
         if (item.Selected)
         {
          selectedLeaveTypes = selectedLeaveTypes + "'" + item.Value + "',";
         }
      }
 selectedLeaveTypes = "(" +selectedLeaveTypes+ ")";

 DataRow[] rows = dt.Select("LeaveType IN '" + selectedLeaveTypes + "'");

语法错误: IN关键字后面的项目必须用逗号分隔,并括在括号中。

2 个答案:

答案 0 :(得分:2)

您已将selectedLeaveType添加到单引号内。删除它们

 DataRow[] rows = dt.Select("LeaveType IN " + selectedLeaveTypes);

单引号将整个变量值转换为单个大文字字符串。

您还需要删除变量

中的最后一个逗号
selectedLeaveTypes = selectedLeaveTypes.TrimEnd(new char[] {','});

我还建议您删除那个大字符串连接并使用带有最终字符串的List<string>。加入以构建IN子句

 List<string> values = new List<string>()
 foreach (ListItem item in chkLeaveType.Items)
 {
     if (item.Selected)
        values.Add("'" + item.Value + "'");
 }
 DataRow[] rows = null;

 // Consider that you should also handle the no selection status
 if(values.Count == 0)
    rows = dt.Select();   // ??
 else
    rows = dt.Select("LeaveType IN (" + 
                  string.Join(",", values.ToArray() + ")");

答案 1 :(得分:0)

var selectedLeaveTypes = "("+String.Join(",", chkLeaveType.Items.Where(item => item.Selected).Select(item => $"'{item.Value}'").ToArray())+")";

DataRow[] rows = dt.Select($"LeaveType IN {selectedLeaveTypes}");