2

datagridviewwinフォームアプリに追加し、CheckBox行をマークするためのアプリも追加しました. CheckBoxユーザーが をソートするまで、期待どおりに動作しますDataGridView。ソート後、チェックボックス列の以前の選択は失われます。

datagridview並べ替え後にどの行が選択されているかを覚えておく方法はありますか?

4

2 に答える 2

4

この問題を解決するには、2つのオプションがあります。

最初の、そしておそらく最も簡単なのは、チェックボックス列をデータソースにバインドすることです。たとえば、データソースとしてDataTableを使用している場合、ブール列を追加すると、DataGridViewにチェックボックスが作成され、チェックされた状態が失われることなく並べ替えられます。

これがオプションでない場合、問題に対処するもう1つの方法は、DataGridViewをVirtualモードに設定し、チェックボックス値のキャッシュを維持することです。

これを行う方法の例については、優れたDataGridViewFAQを確認してください。以下のコードも提供しましたが、FAQを確認してください。

private System.Collections.Generic.Dictionary<int, bool> checkState;
private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.AutoGenerateColumns = false;
    dataGridView1.DataSource = customerOrdersBindingSource;

    // The check box column will be virtual.
    dataGridView1.VirtualMode = true;
    dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn());

    // Initialize the dictionary that contains the boolean check state.
    checkState = new Dictionary<int, bool>();
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // Update the status bar when the cell value changes.
    if (e.ColumnIndex == 0 && e.RowIndex != -1)
    {
        // Get the orderID from the OrderID column.
        int orderID = (int)dataGridView1.Rows[e.RowIndex].Cells["OrderID"].Value;
        checkState[orderID] = (bool)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
    }    
}

private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
    // Handle the notification that the value for a cell in the virtual column
    // is needed. Get the value from the dictionary if the key exists.

    if (e.ColumnIndex == 0)
    {
        int orderID = (int)dataGridView1.Rows[e.RowIndex].Cells["OrderID"].Value;
        if (checkState.ContainsKey(orderID))
            e.Value = checkState[orderID];
        else
            e.Value = false;
    }

}

private void dataGridView1_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
{
    // Handle the notification that the value for a cell in the virtual column
    // needs to be pushed back to the dictionary.

    if (e.ColumnIndex == 0)
    {
        // Get the orderID from the OrderID column.
        int orderID = (int)dataGridView1.Rows[e.RowIndex].Cells["OrderID"].Value;

        // Add or update the checked value to the dictionary depending on if the 
        // key (orderID) already exists.
        if (!checkState.ContainsKey(orderID))
        {
            checkState.Add(orderID, (bool)e.Value);
        }
        else
            checkState[orderID] = (bool)e.Value;
    }
}
于 2010-05-11T22:31:23.327 に答える
1

それが起こることに驚いていますが、最悪の場合、それを回避する方法が他にない場合は、並べ替えをプログラムに設定し、ユーザーが列ヘッダーをクリックしたときに処理し、チェックされている項目のリストを保存して、プログラムで並べ替えてから、チェックする必要がある項目をチェックします。

于 2010-05-08T11:10:40.933 に答える