将列表绑定到包含复选框列的数据网格视图

时间:2018-03-04 16:03:08

标签: c# forms winforms checkbox datagridview

我很难将对象列表绑定到具有复选框列的数据网格视图。

即使我识别出TrueValue和FalseValue,这些值也不会显示。

这就是我做的事情

public class Tree{
  public bool Added{get;set;}
  public string TaskName{get;set;}
  }

在形式上这就是设计师的样子

    private System.Windows.Forms.DataGridViewCheckBoxColumn ClmnCheckBox;
    private System.Windows.Forms.DataGridViewTextBoxColumn ClmnName;
    this.DgvTrees.Location = new System.Drawing.Point(0, 26);
    this.DgvTrees.MultiSelect = false;
    this.DgvTrees.Name = "DgvNoneTasks";
    this.DgvTrees.RowHeadersVisible = false;
    this.DgvTrees.SelectionMode =System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
        this.DgvTrees.Size = new System.Drawing.Size(505, 145);
        this.DgvTrees.TabIndex = 27;
        this.DgvTrees.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvTrees_CellContentClick);
        this.DgvTrees.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvTrees_CellValueChanged);



       this.ClmnCheckBox.DataPropertyName = "Added";
        this.ClmnCheckBox.FalseValue = "false";
        this.ClmnCheckBox.HeaderText = "Add/Remove";
        this.ClmnCheckBox.Name = "ClmnCheckBox";
        this.ClmnCheckBox.TrueValue = "true";
        // 
        // ClmnName
        // 
        this.ClmnName.DataPropertyName = "TaskName";
        this.ClmnName.HeaderText = "Task Name";
        this.ClmnName.Name = "ClmnName";
        this.ClmnName.ReadOnly = true;

这就是我将列表绑定到网格的方式

 var tree= new Tree(){
 Added=true,
 TaskName="task1"
 };
 ListOfTrees.Add(tree);
 DgvTrees.DataSource=ListOfTrees;

现在超过这一点,我得到了记录,但没有勾选复选框。如果我手动检查它,它将被检查,但是一旦我刷新网格,或者对它进行排序,检查就会消失。可能导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:0)

我通过收听事件RowsAdded来修复它,每次通过排序添加天气,或者通过过滤,我将复选框设置为对象布尔值