I want to insert a header checkbox in the datagridview. How can I do select all checkbox header? I am trying this codes but I couldn't succeed it.
C#
private void PersonelEkle_Load(object sender, EventArgs e)
{
Point headerCellLocation = this.dataGridView1.GetCellDisplayRectangle(0, -1, true).Location;
DataGridViewCheckBoxColumn CBColumn = new DataGridViewCheckBoxColumn();
CBColumn.Name = "X";
CBColumn.HeaderText = "ColumnHeader";
CBColumn.Width = 30;
CBColumn.FalseValue = "0";
CBColumn.TrueValue = "1";
dataGridView1.Columns.Insert(0, CBColumn);
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
chk.Value = !(chk.Value == null ? false : (bool)chk.Value); //because chk.Value is initialy null
}
}
Amit MohantyRank #112 · 20K reputationPosted Jun 5, 2023, 8:52 AM EDT
Try this:
private CheckBox headerCheckBox; private void PersonelEkle_Load(object sender, EventArgs e) { // Create the header CheckBox headerCheckBox = new CheckBox(); headerCheckBox.Size = new Size(15, 15); headerCheckBox.CheckedChanged += CheckBox1_CheckedChanged; // Add the header CheckBox to the DataGridView's column header dataGridView1.Controls.Add(headerCheckBox); dataGridView1.Columns[0].HeaderCell.Value = "Select All"; // Adjust the position of the CheckBox to align with the column header Point headerCellLocation = dataGridView1.GetCellDisplayRectangle(0, -1, true).Location; headerCheckBox.Location = new Point(headerCellLocation.X + 8, headerCellLocation.Y + 2); } private void CheckBox1_CheckedChanged(object sender, EventArgs e) { // Update the state of all CheckBox cells in the DataGridView foreach (DataGridViewRow row in dataGridView1.Rows) { DataGridViewCheckBoxCell checkBoxCell = (DataGridViewCheckBoxCell)row.Cells[0]; checkBoxCell.Value = headerCheckBox.Checked; } }Mehmet FatihRank #1,474 · 1.1K reputationPosted Jun 5, 2023, 11:16 AM EDT
Thnaks a lot Amit Mohanty. It was solved. You are wonderful. I am gratefull to you. Everting works fine.
Amit MohantyRank #112 · 20K reputationPosted Jun 5, 2023, 9:42 AM EDT
The "ambiguous reference" error occurs when there are multiple conflicting references to the same class or type. Declare the CheckBox like this:
private System.Windows.Forms.CheckBox headerCheckBox;