Ani
Ani

Reputation: 608

how to display list on datgridview

List A = new List();
A.Add("Apple");
A.Add("Banana");
A.Add("Pineapple");

dataGridView.DataSource = a;

Result: is the length of each item in the list rather than Item itself. 5 6 9 How can I make datagridView to display string instead of length.

Upvotes: 0

Views: 92

Answers (3)

RhysW
RhysW

Reputation: 453

Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this

public class StringValue 
{ 
  public StringValue(string s) 
  { 
      Value = s; 
  } 
  public string Value { get { return _value; } set { _value = value; } } 
  string _value; 
}

Then bind List<StringValue> object to your grid. Just an alternate answer

edit: unintentional complete copy of someone elses answer in a different topic, seems the person who taught me this just copied the answer from there, and a few years later, ive brought it back, unintentional and apologies

Upvotes: 0

Pharabus
Pharabus

Reputation: 6062

you can also do some funky LINQ

List<string> A = new List<string>(); A.Add("Apple"); A.Add("Banana"); A.Add("Pineapple");
dataGridView.DataSource = (from a in A select new {Value = a}).ToList();

edit

To explain a bit further, the issue is that the datagridview is binding to the default property of the object (so a string is length) there is no real property in a string (like value for instance) for you to set DataMember too so you have to create a class, or in my case give it an anonymous class with just one property (or many properties and set DataMember)

Upvotes: 2

Sebastian Br&#243;zda
Sebastian Br&#243;zda

Reputation: 879

create a class, Fruit

class Fruit
{
    public string Name { get; set; }
}

and create a generic list of fruits:

List<Fruit> fruits = new List<Fruit>();
fruits.Add(new Fruit() { Name = "Apple" });

dataGridView1.DataSource = fruits;

Upvotes: 2

Related Questions