修复 DataGridView 的最后一行,即使有人单击列标题对列表进行排序也是如此


Table1     Fig.
Name     | Marks
Pritam   | 80
Aruna    | 85
Uttaran  | 90
Total    | 255
DataTable dtStudentInfo = table1;
dataGridView1.DataSource = dtStudentInfo;

单击列标题名称后,数据网格视图按学生姓名的升序排序。但我希望"总计"行始终保持在列表的末尾。
我想知道是否有任何方法可以从将要排序的列表中删除最后一行。如果这是不可能的,那么建议我可以获得结果的任何方法。注意:我不希望任何外部按钮对列表进行排序。

我通过以下方式解决了这个问题:

DataGridViewRow dgRowTotalCount;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex == -1)
        {
            dgRowTotalCount = (DataGridViewRow)dataGridView1.Rows[((DataGridView)sender).Rows.Count - 1].Clone();
            for (Int32 index = 0; index < ((DataGridView)sender).Rows[((DataGridView)sender).Rows.Count - 1].Cells.Count; index++)
            {
                dgRowTotalCount.Cells[index].Value = ((DataGridView)sender).Rows[((DataGridView)sender).Rows.Count - 1].Cells[index].Value;
            }
            ((DataGridView)sender).Rows.RemoveAt(((DataGridView)sender).Rows.Count - 1);
        }
    }
private void dataGridView1_Sorted(object sender, EventArgs e)
    {
        DataTable dtDGVCopy = new DataTable();
        foreach (DataGridViewColumn col in dataGridView1.Columns)
        {
            dtDGVCopy.Columns.Add(col.Name);
        }
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataRow dRow = dtDGVCopy.NewRow();
            foreach (DataGridViewCell cell in row.Cells)
            {
                dRow[cell.ColumnIndex] = cell.Value;
            }
            dtDGVCopy.Rows.Add(dRow);
        }
        dtDGVCopy.Rows.Add();
        for (Int32 i = 0; i < dgRowTotalCount.Cells.Count - 1; i++)
        {
            dtDGVCopy.Rows[dtDGVCopy.Rows.Count-1][i] = dgRowTotalCount.Cells[i].Value;
        }
        dataGridView1.DataSource = null;
        dataGridView1.DataSource = dtDGVCopy;
    }

但它不像以前那样顺利。如果有什么方法可以让它的性能像以前一样,那就太好了。

我知道

这是一个老问题,但这是我提出的一个解决方案。使用网格上的 SortCompare 事件覆盖特定行的排序:

    private void dgvData_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        if (dgvData.Rows[e.RowIndex1].Cells[0].Value.ToString() == "Total" ||
            dgvData.Rows[e.RowIndex2].Cells[0].Value.ToString() == "Total")
        {
            if (dgvData.SortOrder == SortOrder.Ascending)
            {
                e.SortResult = -1;
            }
            else
            {
                e.SortResult = 1;
            }
            e.Handled = true;
        }
    }

现在,第一列中包含"总计"的任何行将始终排序到网格的末尾。

(如果您允许对列重新排序,则需要弄清楚如何检查正确的列(

最新更新