简体   繁体   中英

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 ?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM