【问题标题】:Datagridview add Checkbox on some cell using <DataGridViewCheckBoxColumn>, not a columnDatagridview 使用 <DataGridViewCheckBoxColumn> 在某些单元格上添加复选框,而不是列
【发布时间】:2017-06-12 05:54:34
【问题描述】:

我有一个绑定到列表的DataGirdView

我想通过DataGridViewCheckBoxCell 在某个单元格上添加CheckBox,但我的datagridview 上没有显示控制器。以下是我的代码:

class ColumnNames
{
    public string Check { get; set; }
    public string Index { get; set; }
    public string SubIndex { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }

    public ColumnNames(
        string Check,
        string Index,
        string SubIndex,
        string Name,
        string Value
        )
    {
        this.Check = Check;
        this.Index = Index;
        this.SubIndex = SubIndex;
        this.Name = Name;
        this.Value = Value;
    }
}

itemsList.Add(new ColumnNames(Check, Index, SubIndex, Name, DataType));
datagridview.DataSource = itemsList;
datagridview.Rows[0].ReadOnly = true;
datagridview.Rows[0].Cells[0] = new DataGridViewCheckBoxCell();
datagridview.Rows[0].Cells[0].Value = false;

当我运行此代码时,我只在单元格 [0] 上得到字符串“假”。 我已经使用断点监视这个单元格,这个单元格是 "Datagirdviewcheckboxcell" ,但没有复选框控制器。 我怎么解决这个问题?谢谢!

【问题讨论】:

  • 因为您将列属性设置为只读,请尝试删除 datagridview.Rows[0].ReadOnly = true;
  • 我可能是错的,但我相信该复选框只能针对布尔属性正确操作。你对班级有控制权吗?你可以添加一个像public bool CheckBool { get { return bool.Parse(this.Check); } set { this.Check = value.ToString(); } } 这样的属性然后绑定到它吗?

标签: c# checkbox datagridview


【解决方案1】:

我想你在这一行中设置了new ColumnNames(Check, Index, SubIndex, Name, DataType) 检查为“字符串”,值为“假”。

将列名更改为:

 ...
 public bool Check { get; set; }
 ...
   public ColumnNames(bool Check, ...)
   {
        this.Check = Check;
        ...
   }
 ...

那么就:

        List<ColumnNames> itemsList = new List<ColumnNames>();
        itemsList.Add(new ColumnNames(true,"Index", "SubIndex", "Name", "DataType"));
        dataGridView1.DataSource = itemsList;

结果:

不需要:datagridview.Rows[0].Cells[0] = new DataGridViewCheckBoxCell();

如果您在一列中需要不同类型的单元格,则必须使用自定义 DataGridViewColumn。

根据这个答案:creating a custom column type? 您有两个教程:

然后在您的类和您的自定义实现中根据值类型绘制单元格中的 Check 属性的对象类型。

类似:

switch(Check.GetType()){
      case typeof(Boolean): /* draw CheckBox */ break;
      default: /* draw string */ break; //you can keep string in default with all other types.
}

【讨论】:

  • 但是当我使用这个类时 public bool Check { get;放; }。我将得到一个列复选框。但我只喜欢有一两行有复选框,其他的没有。
  • 查看我的更新。抱歉没有时间在这里给你写这么复杂的解决方案;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多