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

时间:2011-01-14 13:51:08

标签: c# datagridview anonymous concrete

以下两个代码段填充了稍后分配给的BindingSource 一个DataGridView.DataSource。

当使用具体类QuotesTool.LineItem时(第一个片段),网格不显示相应的数据:

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

但是,如果使用匿名类型,网格将显示数据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
            });
        }

任何想法都将不胜感激。感谢。

1 个答案:

答案 0 :(得分:1)

很难说没有看到QuotesTool.LineItem,但默认很有用,每个成员都有用:

  • 必须公开
  • 必须是属性(不是字段)
  • 不得标记为[Browsable(false)]

这里的问题是通常前两个中的一个。例如,默认情况下,这些都不起作用:

public string Vendor;

internal string Vendor {get;set;}

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

但这会:

public string Vendor {get;set;}

请注意,它不必是自动实现的属性,也不需要是可写的:

private readonly string vendor;
public string Vendor { get { return vendor; } } 
相关问题