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.

1 Answer 1

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; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Marc. Changing class fields to Properties did the trick!
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.