Code Snippet
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
DataTable dt = new DataTable();
private Dictionary<string, bool> store = new Dictionary<string, bool>();
private void Form2_Load(object sender, EventArgs e)
{
dt.Columns.Add("aa", typeof(int));
dt.Columns.Add("bb");
dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(i, "bbb" + i);
}
this.dataGridView1.DataSource = dt.DefaultView;
this.dataGridView1.Columns[0].ReadOnly = true;
this.dataGridView1.VirtualMode = true;
dataGridView1.Columns.Insert(0,new DataGridViewCheckBoxColumn());
dataGridView1.Columns[0].Frozen = true;
//here is the code to check all the checkboxes
for (int i = 0; i < this.dataGridView1.RowCount; i++)
{
if (this.dataGridView1[1, i].Value != null)
{
if (store.ContainsKey(this.dataGridView1[1, i].Value.ToString()))
store[this.dataGridView1[1, i].Value.ToString()] = true;
else
store.Add(this.dataGridView1[1, i].Value.ToString(), true);
}
}
this.dataGridView1.CellValueNeeded += new DataGridViewCellValueEventHandler(dataGridView1_CellValueNeeded);
this.dataGridView1.CellValuePushed += new DataGridViewCellValueEventHandler(dataGridView1_CellValuePushed);
}
private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
if (this.dataGridView1[1, e.RowIndex].Value != null)
{
if (store.ContainsKey(this.dataGridView1[1, e.RowIndex].Value.ToString()))
{
// Use the store if the e value has been modified and stored.
e.Value = store[this.dataGridView1[1, e.RowIndex].Value.ToString()];
}
else
{
e.Value = false;
}
}
}
private void dataGridView1_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
{
if (this.dataGridView1[1, e.RowIndex].Value != null)
{
if (store.ContainsKey(this.dataGridView1[1, e.RowIndex].Value.ToString()))
store[this.dataGridView1[1, e.RowIndex].Value.ToString()] = bool.Parse(e.Value.ToString());
else
store.Add(this.dataGridView1[1, e.RowIndex].Value.ToString(), bool.Parse(e.Value.ToString()));
}
}
}