Mehmet Fatih

Mehmet Fatih

  • 805
  • 904
  • 30.8k

Checkbox initial selection

Jun 7 2023 9:00 PM

 have two problems with the below checkbox codes. One of them is that all checkboxes come as true initially. Second, the header checkbox does not effect the checkbox where the row is selected.

 private void PersonelEkle_Load(object sender, EventArgs e)
        {
            DataGridViewCheckBoxColumn CBColumn = new DataGridViewCheckBoxColumn();
            CBColumn.Width = 30;
            CBColumn.FalseValue = "0";
            CBColumn.TrueValue = "1";
            CBColumn.DataPropertyName = "id";
            CBColumn.ReadOnly = false;
            dataGridView1.Columns.Insert(0, CBColumn);

            Point headerCellLocation = this.dataGridView1.GetCellDisplayRectangle(0, -1, true).Location;
            // Create the header CheckBox
            headerCheckBox = new System.Windows.Forms.CheckBox();
            headerCheckBox.Size = new Size(15, 15);
            headerCheckBox.CheckedChanged += headerCheckBox_CheckedChanged;
            headerCheckBox.Checked = false;

            // Add the header CheckBox to the DataGridView's column header
            dataGridView1.Controls.Add(headerCheckBox);
            headerCheckBox.Location = new Point(headerCellLocation.X + 8, headerCellLocation.Y + 2);

            DoubleBuffered = true;
            Listele();
            }       
        private void headerCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell checkBoxCell = (DataGridViewCheckBoxCell)row.Cells[0];
                checkBoxCell.Value = headerCheckBox.Checked;
            }
        }


Answers (4)