读书人

datagridview多列排序,该如何解决

发布时间: 2012-01-13 22:43:30 作者: rapoo

datagridview多列排序
msdn里有这么一段代码用来多列排序:
private void Button1_Click( object sender, EventArgs e )
{
if ( RadioButton1.Checked == true )
{
DataGridView1.Sort( new RowComparer( SortOrder.Ascending ) );
}
else if ( RadioButton2.Checked == true )
{
DataGridView1.Sort( new RowComparer( SortOrder.Descending ) );
}
}

private class RowComparer : System.Collections.IComparer
{
private static int sortOrderModifier = 1;

public RowComparer(SortOrder sortOrder)
{
if (sortOrder == SortOrder.Descending)
{
sortOrderModifier = -1;
}
else if (sortOrder == SortOrder.Ascending)
{
sortOrderModifier = 1;
}
}

public int Compare(object x, object y)
{
DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;

// Try to sort based on the Last Name column.
int CompareResult = System.String.Compare(
DataGridViewRow1.Cells[1].Value.ToString(),
DataGridViewRow2.Cells[1].Value.ToString());

// If the Last Names are equal, sort based on the First Name.
if ( CompareResult == 0 )
{
CompareResult = System.String.Compare(
DataGridViewRow1.Cells[0].Value.ToString(),
DataGridViewRow2.Cells[0].Value.ToString());


}
return CompareResult * sortOrderModifier;
}
}

我试了没效果,也不懂这段的意思,哪位大哥可以指点一下吗?
在线等啊!急急

[解决办法]
那是因为RowComparer类李德列不是你想指定的列。
DataGridViewRow DataGridViewRow1 = (DataGridViewRow)x;
DataGridViewRow DataGridViewRow2 = (DataGridViewRow)y;

//排序首选列
int CompareResult = System.String.Compare(
DataGridViewRow1.Cells[1].Value.ToString(),
DataGridViewRow2.Cells[1].Value.ToString());

// 排序次级列
if ( CompareResult == 0 )
{
CompareResult = System.String.Compare(
DataGridViewRow1.Cells[0].Value.ToString(),
DataGridViewRow2.Cells[0].Value.ToString());
}

读书人网 >C#

热点推荐