简体   繁体   English

使用DataGridView.DataSource属性和BindingSource填充DataGridView

[英]Populating DataGridView using DataGridView.DataSource property and BindingSource

The following two code snippets populate a BindingSource which is later assigned to a DataGridView.DataSource. 以下两个代码段填充了一个BindingSource,该绑定源随后分配给DataGridView.DataSource。

When the concrete class QuotesTool.LineItem is used (first snippet) the grid DOES NOT display the appropriate data: 当使用具体类QuotesTool.LineItem(第一个代码片段)时,网格不会显示适当的数据:

BindingSource lineList = new BindingSource(); BindingSource lineList = new BindingSource();

        foreach (XElement y in _lines.Elements())
        {
            lineList.Add(new QuotesTool.LineItem(
                y.Element("Vendor").Value,
                y.Element("Model").Value,
                y.Element("Selling_Unit").Value,
                y.Element("Net_Price").Value,
                y.Element("Spec").Value
                       ));
        }

But, if an anonymous type is used the grid displays data OK: 但是,如果使用匿名类型,则网格将显示数据确定:

        foreach (XElement y in _lines.Elements())
        {
            lineList.Add(
              new {
                vendor = y.Element("Vendor").Value,
                Model = y.Element("Model").Value,
                UOM = y.Element("Selling_Unit").Value,
                Price = y.Element("Net_Price").Value,
                Description = y.Element("Spec").Value
            });
        }

Any ideas would be appreciated. 任何想法,将不胜感激。 Thanks. 谢谢。

Hard to tell without seeing QuotesTool.LineItem , but by default to be useful, each member: 很难看到,而无需看到QuotesTool.LineItem ,但默认情况下每个成员QuotesTool.LineItem有用:

  • must be public 必须公开
  • must be a property (not a field) 必须是一个属性(不是字段)
  • must not be marked [Browsable(false)] 不得标记为[Browsable(false)]

The issue here is usually one of the first two. 这里的问题通常是前两个问题之一。 For example, none of these will work by default: 例如,默认情况下,这些都不起作用:

public string Vendor;

internal string Vendor {get;set;}

[Browsable(false)] public string Vendor {get;set;}

but this will: 但这将:

public string Vendor {get;set;}

Note that it doesn't have to be an automatically implemented property, nor does it need to be writeable: 请注意,它不必是自动实现的属性,也不必是可写的:

private readonly string vendor;
public string Vendor { get { return vendor; } } 

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

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