简体   繁体   English

如何将datagridview中的列绑定到c#中的数组元素

[英]How to bind column in datagridview to an array element in c#

I am using C# in Visual Studio 2015. I have a winform with a datagridview.我在 Visual Studio 2015 中使用 C#。我有一个带有 datagridview 的 winform。 I have a custom class我有一个自定义类

   public class deNode
   {
     public byte machine {get;set;}
     public DateTime eDate {get;set;}
     public int[] errorCode {get;set;}
   }

I have :我有 :

List<deNode> equipment;

I want to use equipment as DataSource for the DataGridView and specify errorCode[0],errorCode[1]..errorCode[17] as DataPropertyName s for individual columns in the DataGridView.我想使用设备作为DataGridView DataSource ,并指定errorCode[0],errorCode[1]..errorCode[17]作为 DataGridView 中各个列的DataPropertyName s。

I have tried equipmentGrid.Columns[2].DataPropertyName = "errorCode[2]" but that doesn't work.我已经尝试过equipmentGrid.Columns[2].DataPropertyName = "errorCode[2]"但这不起作用。 How can I achieve my goal?我怎样才能实现我的目标?

appreciate any ideas.欣赏任何想法。

Thanks.谢谢。

Separate your model from the way you display your model.将模型与显示模型的方式分开。 Make something similar to a VideModel , an adapter between the model and the DataGridView.制作类似于VideModel东西,这是模型和 DataGridView 之间的适配器。

Apart from that this solves your problem, it will also make it possible to change your HMI without having to change your model.除此之外,这可以解决您的问题,它还可以更改您的 HMI,而无需更改您的模型。 In future you can (within limits) change your model, without having to change the datagridview.将来您可以(在限制范围内)更改模型,而无需更改数据网格视图。

class ViewModelDeNode
{
    public DeNode DeNode {get; set;}

    public int ErrorCode00 => this.DeNode.ErrorCode[00];
    public int ErrorCode01 => this.DeNode.ErrorCode[01];
    ...
}

The columns in your DataGridView:您的 DataGridView 中的列:

DataGridViewColumn columnErrorCode01 = new DataGridViewColumn()
{
    Name = ...
    HeaderText = "Error code 01",
    DataPropertyName = nameof(ViewModelDenode.ErrorCode01),
    ...
};


IEnumerable<DeNode> deNodes = ...
IEnumerable<ViewModelDenode> displayableDeNodes = deNodes
    .Select(deNode => new ViewModelDeNode
    {
        DeNode = deNode,
    });

DataGridView dgv = new DataGridView(...);
dgv.DataSource = displayableDeNodes.ToList();

Or if you want to edit the datagridview (add / remove / update rows):或者,如果您想编辑 datagridview(添加/删除/更新行):

dgv.DataSource = new BindingList<ViewModelDeNode>(displayableDeNodes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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