我有数据表显示不同时期不同城市的统计数据。它具有以下列名称
Period | city1,state | city2,state | city3,state
Jan 15 25 20
Feb 5 26 29
Mar 35 27 21
我已经应用了一些逻辑,它给了我列名来对相应的列名进行排序,并再次将数据与前端的网格绑定(bind)。
当我尝试使用以下代码进行排序时,问题来了
griData.DefaultView.Sort = string.Format("{0} {1}", orderByField, sortDirection)
由于列名中的逗号,它将其视为两列并给出异常(exception)。 示例: 如果我按 city1,state 列升序排序,则排序表达式将为 city1,state asc 并且在执行该语句时它会抛出 city1 列不存在的异常' 存在而不是排序。谢谢
最佳答案
尝试以这种方式改变你的格式
griData.DefaultView.Sort = string.Format("[{0}] {1}", orderByField, sortDirection)
处理包含保留字符的列名的通常方法是将名称括在方括号中。
编辑 我无法找到这种情况的解决方法。 (当然,使用这种名称是一个错误的决定,但老实说,我相信方括号可以解决这个问题)
到目前为止发现的唯一可能的解决方法是以某种方式更改您的查询,为您的列名创建一个别名,然后您可以对这些别名进行排序。像这样的东西
SELECT Period,
[city1,state] AS City1State,
[city2,state] AS City2State,
[city3,state] AS City3State
FROM yourTable
....
orderByField = "City1State"
sortDirection = "DESC"
griData.DefaultView.Sort = string.Format("{0} {1}", orderByField, sortDirection)
再次编辑 您的问题确实引起了我的好奇心,因此我搜索了用于 DataView 的 Sort 属性的代码并找到了一个似乎有罪的内部方法。它在逗号处拆分排序字符串,并完全忽略字符串周围的任何方括号。因此,似乎没有办法使用该名称。
DataView 的排序属性代码......
internal unsafe IndexField[] ParseSortString(string sortString)
{
string str;
int num;
int num2;
string[] strArray;
IndexField[] fieldArray;
DataColumn column;
bool flag;
char[] chArray;
fieldArray = zeroIndexField;
if (sortString == null)
{
goto Label_011A;
}
if (0 >= sortString.Length)
{
goto Label_011A;
}
// Here the split on the comma char (0x2C) ignoring the fact that
// the whole sort expression is inside square brackets????
strArray = sortString.Split(new char[] { 0x2c });
fieldArray = new IndexField[(int) strArray.Length];
num2 = 0;
goto Label_0111;
Label_0041:
str = strArray[num2].Trim();
num = str.Length;
flag = 0;
if (num < 5)
{
goto Label_007D;
}
if (string.Compare(str, num - 4, " ASC", 0, 4, 5) != null)
{
goto Label_007D;
}
str = str.Substring(0, num - 4).Trim();
goto Label_00A7;
Label_007D:
if (num < 6)
{
goto Label_00A7;
}
if (string.Compare(str, num - 5, " DESC", 0, 5, 5) != null)
{
goto Label_00A7;
}
flag = 1;
str = str.Substring(0, num - 5).Trim();
Label_00A7:
if (str.StartsWith("[", 4) == null)
{
goto Label_00DE;
}
if (str.EndsWith("]", 4) == null)
{
goto Label_00D5;
}
str = str.Substring(1, str.Length - 2);
goto Label_00DE;
Label_00D5:
throw ExceptionBuilder.InvalidSortString(strArray[num2]);
Label_00DE:
column = this.Columns[str];
if (column != null)
{
goto Label_00F7;
}
throw ExceptionBuilder.ColumnOutOfRange(str);
Label_00F7:
*(&(fieldArray[num2])) = new IndexField(column, flag);
num2 += 1;
Label_0111:
if (num2 < ((int) strArray.Length))
{
goto Label_0041;
}
Label_011A:
return fieldArray;
}
关于c# - DataTable 使用带逗号的 Datacolumn Name 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22097203/