之前做记账程序时用了DataGridView来呈现数据,为了提升用户体验,在显示数据时我还在最后一行加了一个统计行。又因为DataGridView是可以点击标题行来排序的,当用户点击排序时最后的统计行也会跟着排序,变到其他行去了,这样很不爽。
于是就要想一个办法让最后一行不参与排序,DataGridView本身没有这样的方法,得自己实现。搜索之后得到一个思路:在排序前先保存最后一行,然后删除之,排序后再添加回来。
要用到两个事件,CellMouseClick和Sorted事件,C#代码如下:
注意:上面的代码只适用于没有使用数据绑定的DataGridView,否则在执行到dataGridView1.Rows.Add时会出现 当控件被数据绑定时,无法以编程方式向 DataGridView 的行集合中添加行的错误。
下面是另一种方法,当DataGridView使用了DataTable作为数据源绑定时,在Sorted事件里写代码对DataTable排序,然后再重新绑定到DataGridView中,代码如下:
于是就要想一个办法让最后一行不参与排序,DataGridView本身没有这样的方法,得自己实现。搜索之后得到一个思路:在排序前先保存最后一行,然后删除之,排序后再添加回来。
要用到两个事件,CellMouseClick和Sorted事件,C#代码如下:
private void lwolf_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0 || lwolf.Rows.Count == 0)
return;
if (lastRow.Count <= 0)
{
int index = lwolf.Rows.Count - 1;
lastRow.Add(lwolf.Rows[index]);
lwolf.Rows.RemoveAt(index);
}
}
private List<DataGridViewRow> lastRow = new List<DataGridViewRow>();
private void lwolf_Sorted(object sender, EventArgs e)
{
if (lastRow.Count <= 0)
return;
lwolf.Rows.Add(lastRow[0]);
lastRow.Clear();
}
注意:上面的代码只适用于没有使用数据绑定的DataGridView,否则在执行到dataGridView1.Rows.Add时会出现 当控件被数据绑定时,无法以编程方式向 DataGridView 的行集合中添加行的错误。
下面是另一种方法,当DataGridView使用了DataTable作为数据源绑定时,在Sorted事件里写代码对DataTable排序,然后再重新绑定到DataGridView中,代码如下:
List<object[]> lastRow = new List<object[]>();
int colindex = 0;
private void lwolf_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0 || lwolf.Rows.Count == 0)
return;
if (lastRow.Count == 0)
{
colindex = e.ColumnIndex;
int index = lwolf.Rows.Count - 1;
lastRow.Add(((DataTable)lwolf.DataSource).Rows[index].ItemArray);
lwolf.Rows.Remove(lwolf.Rows[lwolf.Rows.Count - 1]);
}
}
private void lwolf_Sorted(object sender, EventArgs e)
{
if (lastRow.Count == 0)
return;
DataTable dt=((DataTable)lwolf.DataSource);
DataView dv = dt.DefaultView;
dv.Sort = dt.Columns[colindex].ColumnName;
dt = dv.ToTable ();
dt.Rows.Add(lastRow[0]);
lastRow.Clear();
lwolf.DataSource = dt;
}