DataGridView复选框选择

时间:2010-05-08 11:01:37

标签: c# winforms datagridview datagridviewcheckboxcell

我将datagridview添加到我的win表单应用程序中,并且我还添加了一个CheckBox来标记行。 CheckBox按预期工作,直到用户对DataGridView进行排序。排序后,复选框列的上一个选择将丢失。

有没有办法让datagridview记住排序后选择哪一行?

2 个答案:

答案 0 :(得分:4)

您有两种方法可以解决此问题。

第一个也可能是最简单的是将复选框列绑定到数据源。例如,如果您使用DataTable作为数据源,则添加布尔列将在DataGridView上创建一个复选框,该复选框将排序并且不会丢失已检查状态。

如果这不是一个选项,那么解决问题的另一种方法是将DataGridView设置为Virtual模式并维护复选框值的缓存。

查看优秀的DataGridView 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;
    }
}

答案 1 :(得分:1)

我很惊讶发生了这种情况,但如果在最坏的情况下没有别的方法可以将排序设置为编程,然后在用户点击列标题时进行处理,保存检查了哪些项目的列表,以编程方式进行排序,然后检查应检查的任何项目。

相关问题