DataGridView最后一行不排序的方法

       之前做记账程序时用了DataGridView来呈现数据,为了提升用户体验,在显示数据时我还在最后一行加了一个统计行。又因为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;
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值