【问题标题】:Populating DataGridView using DataGridView.DataSource property and BindingSource使用 DataGridView.DataSource 属性和 BindingSource 填充 DataGridView
【发布时间】:2011-01-14 13:51:08
【问题描述】:

下面的两个代码 sn-ps 填充了一个 BindingSource,稍后将其分配给 一个 DataGridView.DataSource。

当使用具体类 QuotesTool.LineItem(第一个 sn-p)时,网格不会显示适当的数据:

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

但是,如果使用匿名类型,则网格显示数据正常:

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

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

【问题讨论】:

    标签: c# datagridview anonymous concrete


    【解决方案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; } } 
    

    【讨论】:

    • 谢谢马克。将类字段更改为属性就可以了!
    • @user575719 好;老实说,公共领域普遍是个坏主意。如果这回答了您的问题,请考虑点击答案旁边的绿色“对勾”,将其标记为完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多