Raj De Inno Raj De Inno - 1 month ago 15
C# Question

Bind different lists into columns in datagridview in c#

I have dynamic list item. This list is not static. In view of the necessity, I will have at least one/more list. what I need is, I gotta split that list into at least two unique records. This I can part. Yet, I need to bind this list into datagridview.

This is my code: I have two list,

List<string> list1=new List<string>();
list1.add("THE BOOK OF BURGER");
list1.add("The Hogwarts Library");
list1.add("NEW Day in the Life of a Farmer");

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

list4.. etc..

I have Datagridview. I want to bind this into data grid view as,
enter image description here

how might I add datasource to this datagridview? I tired to include this into datatable. In any case, I couldn't accomplish this. Any help would be truly valued.


You can create a BooK class and shape your data in a List<Book> and bind the grid to the list.


public class Book
    public string Title { get; set; }
    public string Price { get; set; }

Bind data to DataGridView

var list = new List<Book>();
for (int i = 0; i < list1.Count; i++)
    list.Add(new Book()
        Title = list1[i],
        Price = list2[i]

this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = list;


Based on comments, I suppose you have a Dictionary<String, List<String>> and you want to add them dynamically to the grid.

I suppose you will use the key of dictionary as header text for the column.

//Add your lists to the dictionary
var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("list1", list1);
dictionary.Add("list2", list2);
// And some othet lists ....

//Calculate the count of rows.
int rowCount = dictionary.Cast<KeyValuePair<string, List<string>>>()

//Create the data table and for each table, add a column
var dataTable = new DataTable();
foreach (var key in dictionary.Keys)

//Add items of each list to the columns of rows of table
for (int i = 0; i < rowCount; i++)
    var row = dataTable.Rows.Add();
    foreach (var key in dictionary.Keys)
            row[key] = dictionary[key][i];
            row[key] = null;

//Show data in grid
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = dataTable;

and here is the result:

enter image description here