Home > Net >  Checkbox column not getting checked in datagridview c#
Checkbox column not getting checked in datagridview c#

Time:06-28

I have added checkbox column in datagridview and i want that checkboxes checked if one of my column value == 1 otherwise the checkbox should be unchecked i have written following code where content loads in datagridview and that method is called at form load event but checkboxes not showing checked when first time that method is calling when method gets called second time that is working correct

DataGridViewCheckBoxColumn chkboxcolumn = new DataGridViewCheckBoxColumn();
chkboxcolumn.HeaderText = "";
chkboxcolumn.Width = 30;
chkboxcolumn.Name = "checkBoxColumn";

      if (!dgvCompany.Columns.Contains(chkboxcolumn.Name))
      {
            dgvCompany.Columns.Insert(0, chkboxcolumn);
      }
               
      for (int i = 0; i < dgvCompany.Rows.Count; i  )
      {
            if (Convert.ToString (dgvCompany.Rows[i].Cells["CompanyLead"].Value) == "1")
            {
                   dgvCompany.Rows[i].Cells["checkBoxColumn"].Value = true;
                        
            }
      }

CodePudding user response:

Try to change the

dgvCompany.Rows[i].Cells["checkBoxColumn"].Value = true;

for

dgvCompany.Rows[i].Cells["checkBoxColumn"].Checked = true;

if the checked not appear in the IDE, try to cast this cell to a checkbox

var test = (Checkbox)dgvCompany.Rows[i].Cells["checkBoxColumn"];

test.Checked = true;

CodePudding user response:

Is what I am getting at is that if the grids DataSource is a DataTable AND the CompanyLead column in the data table is of a string type, then simply add the code below to add a bool “Expression” column to the existing table. DataColumn.Expression Property

With this, then ALL the posted code you have shown becomes unnecessary. Something like…

ds.Tables[0].Columns.Add("CheckBoxColumn", typeof(bool), "IIF(CompanyLead = 1, true, false)");
  • Related