2010-05-08 118 views
2

我将datagridview添加到我的获奖形式应用程序中,并且还为标记行添加了一个CheckBoxCheckBox按我的预期工作,直到用户对DataGridView进行排序。排序之后,之前选中的复选框列丢失。DataGridView复选框选择

有没有一种方法可以让我的datagridview记住排序后选择哪一行?

回答

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; 
    } 
} 
+0

Thanx同样的行为答案也FAQ,你是正确的绑定布尔列到数据源,还有一个问题?我应该携带来自原始数据源(StoredProc)的布尔列,还是在将数据绑定到我的网格之前在客户端级别添加更好的方法 – adopilot 2010-05-12 06:46:57

1

我很惊讶,发生这种情况,但如果在最坏的情况下没有其他解决方法,您可以将排序设置为编程方式,然后在用户单击列标题时处理,保存列表中的项目选中,以编程方式进行分类,然后检查应检查的项目。

+0

我很惊讶也一样,在杉杉我在想,我做错了什么,然后我资助这篇文章中的http://www.dotnetspark。 com/kb/Content.aspx?id = 151和发现DataGridView – adopilot 2010-05-08 11:29:06