我有数据表显示不同时期不同城市的统计数据.它具有以下列名称
Period | city1,state | city2,state | city3,state
Jan 15 25 20
Feb 5 26 29
Mar 35 27 21
我已经应用了一些逻辑,它给我列名称来对相应的列名进行排序,并使用前端的网格再次绑定数据.
现在,当我尝试使用以下代码进行排序时出现问题
griData.DefaultView.Sort = string.Format("{0} {1}", orderByField, sortDirection)
由于列名中的逗号,它将其视为两列并提供异常.示例:如果我按列city1排序,则按升序进行排序,然后排序表达式将为city1,state asc,并且在执行语句时,它会抛出一个异常,即city 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的Sort属性的代码…..
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;
}