我添加datagridview
到我的 win forms 应用程序中,还添加了一个CheckBox
用于标记行。在CheckBox
用户对DataGridView
. 排序后,先前选择的复选框列将丢失。
有没有办法让我datagridview
记住排序后选择了哪一行?
我添加datagridview
到我的 win forms 应用程序中,还添加了一个CheckBox
用于标记行。在CheckBox
用户对DataGridView
. 排序后,先前选择的复选框列将丢失。
有没有办法让我datagridview
记住排序后选择了哪一行?
您有两种选择来解决此问题。
第一个可能也是最简单的是将复选框列绑定到数据源。例如,如果您使用 DataTable 作为数据源,添加布尔列将在 DataGridView 上创建一个复选框,该复选框将排序并且不会丢失选中状态。
如果这不是一个选项,那么解决问题的另一种方法是将 DataGridView 设置为Virtual
模式并维护复选框值的缓存。
查看出色的DataGridView 常见问题解答,了解如何执行此操作的示例。我还提供了下面的代码,但请查看常见问题解答:
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;
}
}
我很惊讶会发生这种情况,但是如果在最坏的情况下没有其他方法可以解决它,您可以将排序设置为编程,然后在用户单击列标题时进行处理,保存检查项目的列表,执行以编程方式排序,然后检查应检查的任何项目。