我添加了 datagridview 在我的获胜表格应用程序中,我还添加了一个 CheckBox 用于标记行。这 CheckBox 在用户分类之前,我会按照我的期望进行工作 DataGridView. 。排序之后,先前选择的复选框列会丢失。

有什么方法我可以做我的 datagridview 记得排序后选择了哪一行?

有帮助吗?

解决方案

您有两个选择解决此问题。

第一个也是最简单的是将复选框列绑定到数据源。例如,如果您使用数据词作为数据源,则添加布尔值列将在您的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;
    }
}

其他提示

我很惊讶这种情况会发生,但是如果在最坏的情况下没有其他方法,您可以将分类设置为程序化,然后在用户单击“列标头”时处理,保留检查哪些项目的列表,请执行以编程方式进行分类,然后检查应检查的所有项目。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top