如何在C#

时间:2016-06-15 12:06:44

标签: c# datagridview datagridviewcolumn

当我根据从数据库中检索到的值加载表单时,我试图填充我插入datagridview的复选框,但它不起作用。

这是一个假期详细的表格,它应该给我所有的假期,如果它是循环或不循环。

这是我写的代码

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;
    }
}

这就是运行代码后的结果

the is cycled should be ticked

1 个答案:

答案 0 :(得分:0)

将布尔数据列添加到DataTable,而不是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;
}