BILL
BILL

Reputation: 4869

How to dynamically set source of DataGridView in C#?

I have some List for storage data

List<List<string>> data = new List<List<string>>();

How to correctly assign it to dataGridView.DataSource ?

Upvotes: 0

Views: 1721

Answers (2)

Jay Riggs
Jay Riggs

Reputation: 53595

The problem here is (obviously) the DataGridView DataSource property doesn't know how to display a List<List<string>>. One approach is to combine your Lists into one object which the DataGridView can bind to. Here are a couple ways to do this:

To a DataTable:

To convert your List<List<string>> to a DataTable, I borrowed the code found here and created this extension method:

static class ListExtensions { 
    public static DataTable ToDataTable(this List<List<string>> list) { 
        DataTable tmp = new DataTable();
        tmp.Columns.Add("MyData");
        // Iterate through all List<string> elements and add each string value to a new DataTable Row.        
        list.ForEach(lst => lst.ForEach(s => tmp.Rows.Add(new object[] {s})));

        return tmp; 
    } 
}

Here's now you can use this extension method to get a DataTable from your List<List<string>> which you can bind to your DataGridView:

dataGridView.DataSource = data.ToDataTable();

To an anonymous type List:

Here is the code for doing this:

dataGridView.DataSource = data.SelectMany(lst => lst)
                              .Select(s => new { Value = s }).ToList();

We need the anonymous type because a DataGridView won't be able to display the string values in List property without a little help, as described here.


There are of course disadvantages to either these approaches but I do believe something along these lines is your best option.

Upvotes: 1

Paul Sullivan
Paul Sullivan

Reputation: 2875

List<List<string>> data = new List<List<string>>();
dataGridView.DataSource = data;
dataGridView.Databind();

as some posters stated this was for windows forms in which case you can (according to MSDN) jst set the datasurce and not databind

Upvotes: 1

Related Questions