.NET / C# Binding IList<string> to a DataGridView
Asked Answered
Y

2

7

I have an IList<string> returning from a function (as variable lst) and I set and then I

this.dataGridView1.DataSource = lst;

The datagrid adds one column labelled Length and then lists the length of each string. How do I make it just list the strings?

Yousuf answered 9/7, 2009 at 14:45 Comment(2)
Does your IList contain only Strings? or does it contain some other type, <T>?Fenestra
uh...he said it's an IList<string>...Novgorod
S
14

You really need a list of objects that have a string property. With .NET 3.5 you could cheat:

.DataSource = list.Select(x=>new {Value = x}).ToList();

Otherwise create a dummy class and copy the data in manually...

Speedy answered 9/7, 2009 at 14:58 Comment(1)
Exactly what I was looking for, anonymous types are great for this sort of thing.Goodbye
W
2

This is because DataGridViews show properties of the object. In this case the List only has one property "Length", therefore it can only display "Lenght" (regardless of DataType). You need to create a wrapper class to achieve what you want (a "MyString" class with a property of "Text", then have a List displayed in your grid).

Hope this helps

Adding Code Example

 class MyString
    {
        private string _text;
        public string Text
        { get 
             { 
              return _text; 
             }
            set 
            {
                _text = value; 
            }
        }

    }

'In the executing form

 private List<MyString> foo()
        {
            List<MyString> lst = new List<MyString>();
            MyString one = new MyString();
            MyString two = new MyString();
            one.Text = "Hello";
            two.Text = "Goodbye";
            lst.Add(one);
            lst.Add(two);
            return lst;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = foo();

        }
Whatever answered 9/7, 2009 at 15:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.