1

The following two code snippets populate a BindingSource which is later assigned to a DataGridView.DataSource.

When the concrete class QuotesTool.LineItem is used (first snippet) the grid DOES NOT display the appropriate data:

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.

user575719
  • 11
  • 1

1 Answers1

1

Hard to tell without seeing QuotesTool.LineItem, but by default to be useful, each member:

  • must be public
  • must be a property (not a field)
  • must not be marked [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; } } 
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks Marc. Changing class fields to Properties did the trick! – user575719 Jan 14 '11 at 14:38
  • @user575719 good; public fields are *universally* a bad idea, to be honest. If this answers your question, please consider clicking the green "tick" to next to the answer, to mark it complete. – Marc Gravell Jan 14 '11 at 15:24