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 t开发者_运维百科o display string instead of length.
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;
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)
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
精彩评论