按代码修改C#组以允许字段名称中的空格

时间:2013-01-24 13:34:41

标签: c# winforms

这是参考本回答中提供的代码:@ {Timmer Schmelter的enter link description here

代码是按特定列对DataTable进行分组,并向列(pivot)添加计数:

   public DataTable GroupBy(string i_sGroupByColumn, string i_sAggregateColumn, DataTable i_dSourceTable)
    {

        DataView dv = new DataView(i_dSourceTable);

        //getting distinct values for group column
        DataTable dtGroup = dv.ToTable(true, new string[] { i_sGroupByColumn });

        //adding column for the row count
        dtGroup.Columns.Add("Count", typeof(int));

        //looping thru distinct values for the group, counting
        foreach (DataRow dr in dtGroup.Rows)
        {
            dr["Count"] = i_dSourceTable.Compute("Count(" + i_sAggregateColumn + ")", i_sGroupByColumn + " = '" + dr[i_sGroupByColumn] + "'");
        }

        //returning grouped/counted result
        return dtGroup;
    }

但是,我的数据表有一个列(我不能改变这个),在字段名称中有一个空格,即:“解决方案ID”

当我将其传递给上面的代码时,请使用:

DataTable Solutions = GroupBy("Solution ID", "Solution ID", tbQ);

...我收到错误:语法错误:'ID'运算符后缺少操作数。

我尝试使用[]封装,将空格修改为+,但它不起作用。

是否可以修改上面的代码,接受其中有空格的列?

谢谢Mark,

1 个答案:

答案 0 :(得分:1)

  

我尝试使用[]封装,将空格修改为+,但它不起作用。

将空间改为+肯定不会起作用,但应该用括号括起来。尝试

if(!i_sAggregateColumn.StartsWith("["))
    i_sAggregateColumn = "[" + i_sAggregateColumn + "]";

if(!i_sGroupByColumn.StartsWith("["))
    i_sGroupByColumn = "[" + i_sGroupByColumn + "]";

请注意,如果您的列名已包含括号you'll have to try something else