我將datagridview
添加到我的獲獎形式應用程序中,並且還爲標記行添加了一個CheckBox
。 CheckBox
按我的預期工作,直到用戶對DataGridView
進行排序。排序之後,之前選中的複選框列丟失。DataGridView複選框選擇
有沒有一種方法可以讓我的datagridview
記住排序後選擇哪一行?
我將datagridview
添加到我的獲獎形式應用程序中,並且還爲標記行添加了一個CheckBox
。 CheckBox
按我的預期工作,直到用戶對DataGridView
進行排序。排序之後,之前選中的複選框列丟失。DataGridView複選框選擇
有沒有一種方法可以讓我的datagridview
記住排序後選擇哪一行?
您有兩個選擇來解決這個問題。
第一個也可能是最簡單的是將您的複選框列綁定到您的數據源。例如,如果您使用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;
}
}
我很驚訝,發生這種情況,但如果在最壞的情況下沒有其他解決方法,您可以將排序設置爲編程方式,然後在用戶單擊列標題時處理,保存列表中的項目選中,以編程方式進行分類,然後檢查應檢查的項目。
我很驚訝也一樣,在杉杉我在想,我做錯了什麼,然後我資助這篇文章中的http://www.dotnetspark。 com/kb/Content.aspx?id = 151和發現DataGridView – adopilot 2010-05-08 11:29:06
Thanx同樣的行爲答案也FAQ,你是正確的綁定布爾列到數據源,還有一個問題?我應該攜帶來自原始數據源(StoredProc)的布爾列,還是在將數據綁定到我的網格之前在客戶端級別添加更好的方法 – adopilot 2010-05-12 06:46:57