使用DataView过滤返回语法错误

时间:2019-07-09 16:52:06

标签: c# winforms datatable

我从存储过程中接收数据,例如:

       var db = new SQLConnMgr();
       var dtJobs = db.GetTableBySQL(sp);

一旦我有数据,我就将其分为两个数据列,并插入到两个不同的数据表中,例如:

            DataColumn[] projectsColumns = dtJobs.Columns.Cast<DataColumn>()
    .Where(c => c.ColumnName == "Project Name" || c.ColumnName == "ProjectKey")
    .Select(c => new DataColumn(c.ColumnName, c.DataType))
    .ToArray();

            DataColumn[] designGroupColumns = dtJobs.Columns.Cast<DataColumn>()
  .Where(c => c.ColumnName == "DesignGroup Name" || c.ColumnName == "DesignGroupId")
  .Select(c => new DataColumn(c.ColumnName, c.DataType))
  .ToArray();

            this.Projects = new DataTable();
            this.Projects.Columns.AddRange(projectsColumns);
            this.DesignGroups = new DataTable();
            this.DesignGroups.Columns.AddRange(designGroupColumns);


            foreach (DataRow row in dtJobs.Rows)
            {
                DataRow aRow = Projects.Rows.Add();
                DataRow bRow = DesignGroups.Rows.Add();
                foreach (DataColumn project in projectsColumns)
                    aRow.SetField(project, row[project.ColumnName]);
                foreach (DataColumn designGroup in designGroupColumns)
                    bRow.SetField(designGroup, row[designGroup.ColumnName]);
            }

所以现在我有两个具有不同数据和列的数据表。现在,我想在文本框更改事件中过滤项目Datatable。所以我这样做:

  private void txtSearchJobName_TextChanged(object sender, EventArgs e)
        {
            DataView dvJobs = this.Projects.DefaultView;
            dvJobs.RowFilter = "Project Name LIKE '%" + txtSearchJobName.Text + "%'";
        }

但是当我在文本框中键入内容时,它会返回语法错误错误

  

System.Data.SyntaxErrorException:'语法错误:之后缺少操作数   “名称”运算符。”

当我尝试执行dvJobs.RowFilter,调试dvJobs DataView并且它有我的Project Name列时,就会发生这种情况,我不知道我在语法上做错了什么。问候

2 个答案:

答案 0 :(得分:1)

将事件处理程序中的代码更改为

private void txtSearchJobName_TextChanged(object sender, EventArgs e)
{
    DataView dvJobs = this.Projects.DefaultView;
    dvJobs.RowFilter = "[Project Name] LIKE '%" + txtSearchJobName.Text + "%'";
}

解析器对包含空格的列名称感到困惑,因此您需要将其名称括在方括号之间。

对此,我建议将创建两个数据表的代码更改为更简单的

 DataTable dtProjects = dtJobs.DefaultView.ToTable(false, 
                               new string[] {"ProjectKey", "Project Name"});
 DataTable dtDesign  = dtJobs.DefaultView.ToTable(false, 
                               new string[] {"DesignGroup Name","DesignGroupId"});

这不仅创建了两个表,而且还复制了原始表中的数据。参见DataView.ToTable

答案 1 :(得分:0)

过滤器语法为:“ ColumnName操作数值”。

尝试:dvJobs.RowFilter =“名称类似'%” + txtSearchJobName.Text +“%'”;

示例和更多信息可以在这里找到:https://docs.microsoft.com/de-de/dotnet/api/system.data.datacolumn.expression?view=netframework-4.8