当datagridview列自动排序时会触发什么事件?

时间:2016-03-25 02:28:49

标签: c# sorting events datagridview datagrid

我有以下代码在用户进行更改时突出显示单元格。

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        int selectedRow = e.RowIndex;
        int selectedCol = e.ColumnIndex;

        if (selectedRow >= 0 && selectedCol >=0 )
        {
            dataGridView1[selectedCol, selectedRow].Style.BackColor = Color.Yellow;
        }
    }

用户可以在更新单元格之前对列进行排序。在更新之前,数据看起来像这样(注意价格列按升序排序):

我将40.98美元改为45美元。 datagrid会自动排序。突出显示的单元格是更新的调用最初所在的位置。包含45美元的新单元格未突出显示。

更新和自动排序后的Datagrid:

在自动排序过程中不会触发datagrid的Sorted事件。有人可以告诉我演出解决问题吗?谢谢!

2 个答案:

答案 0 :(得分:0)

ListChanged(类型ItemMoved)事件被触发

答案 1 :(得分:0)

我遇到了同样的问题,我使用这种方式:

我已经在以下形式的类中声明了一个私有变量:

private string id = string.Empty;

然后是我的CellValueChanged方法

private void dgvOggetto_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
// other code

            ID = dataGridView.Rows[dataGridView.CurrentCell.RowIndex].Cells["ID"].Value.ToString();
        }

并且我使用了SelectionChanged方法

private void dgvOggetto_SelectionChanged(object sender, EventArgs e)
        {
// avoid fire the event if the Tag contains a keyword
            if (dataGridView.Tag.ToString().Contains("updating")) return;

            if (!string.IsNullOrEmpty(ID))
            {
//find the row
                DataGridViewRow row = dataGridView.Rows
                    .Cast<DataGridViewRow>()
                    .FirstOrDefault(r => r.Cells["ID"].Value.ToString().Equals(id));

                if (row != null)
                {
//select the row 
                    dataGridView.Rows[row.Index].Selected = true;
                    dataGridView.Rows[row.Index].Cells[0].Selected = true;

                    // place the current row in the middle
                    dataGridView.FirstDisplayedScrollingRowIndex = (row.Index - (dataGridView.Height - dataGridView.ColumnHeadersHeight) / dataGridView.RowTemplate.Height / 2) > 0 ? row.Index - (dataGridView.Height - dataGridView.ColumnHeadersHeight) / dataGridView.RowTemplate.Height / 2 : 0;
                }

// clean ID variable
                ID = string.Empty;
            }
        }