简体   繁体   中英

How to populate CheckBox column dynamically in C#

I am trying to populate the checkbox I inserted into datagridview when the form load based on values I retrieved from the database, but it doesn't work.

It's a vacation detailed form and it should give me all the vacation and if it is cycled or not.

This is the code I wrote

constr = conn.createNewConnection();

da = new SqlDataAdapter(selectCommand, constr);

ds = new System.Data.DataSet();
da.Fill(ds,"vacation_tbl");
vacGrid.DataSource = ds.Tables[0];
vacGrid.Columns[2].Visible = false;

vacGrid.Columns[0].HeaderText = "Vacation Code";
vacGrid.Columns[0].Width = 100;
vacGrid.Columns[1].HeaderText = "Vacation Name";
vacGrid.Columns[1].Width = 100;
//vacGrid.Columns[3].HeaderText = " System User";

checkBoxColumn.HeaderText = "Is Cycled";
checkBoxColumn.Width = 100;
checkBoxColumn.Name = "cyclechbx";
vacGrid.Columns.Insert(3, checkBoxColumn);

int IsCycel;

for(int i = 0; i < vacGrid.Rows.Count; i++)
{
    IsCycel = Convert.ToInt32(vacGrid.Rows[i].Cells[2].Value);

    if (IsCycel == 1)
    {
        vacGrid["cyclechbx", i].Value = true;
    }
}

and this is what it results after run the code

the is cycled should be ticked

Add boolean DataColumn to DataTable, not DataGridView.

da.Fill(ds,"vacation_tbl");
ds.Tables[0].Columns.Add("cyclechbx", typeof(bool)); // here
vacGrid.DataSource = ds.Tables[0];
vacGrid.Columns[2].Visible = false;

vacGrid.Columns[0].HeaderText = "Vacation Code";
vacGrid.Columns[0].Width = 100;
vacGrid.Columns[1].HeaderText = "Vacation Name";
vacGrid.Columns[1].Width = 100;

// 3 - the index of the bool column. Change it if necessary.
vacGrid.Columns[3].HeaderText = "Is Cycled";
vacGrid.Columns[3].Width = 100;
vacGrid.Columns[3].Name = "cyclechbx";

for (int i = 0; i < vacGrid.Rows.Count; i++)
{
    vacGrid["cyclechbx", i].Value = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM