datagridview
winフォームアプリに追加し、CheckBox
行をマークするためのアプリも追加しました. CheckBox
ユーザーが をソートするまで、期待どおりに動作しますDataGridView
。ソート後、チェックボックス列の以前の選択は失われます。
datagridview
並べ替え後にどの行が選択されているかを覚えておく方法はありますか?
datagridview
winフォームアプリに追加し、CheckBox
行をマークするためのアプリも追加しました. CheckBox
ユーザーが をソートするまで、期待どおりに動作しますDataGridView
。ソート後、チェックボックス列の以前の選択は失われます。
datagridview
並べ替え後にどの行が選択されているかを覚えておく方法はありますか?
この問題を解決するには、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;
}
}
それが起こることに驚いていますが、最悪の場合、それを回避する方法が他にない場合は、並べ替えをプログラムに設定し、ユーザーが列ヘッダーをクリックしたときに処理し、チェックされている項目のリストを保存して、プログラムで並べ替えてから、チェックする必要がある項目をチェックします。