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>();
list2.add("$200");
list2.add("$150");
list2.add("$170");
.....
list3,
list4.. etc..
I have Datagridview. I want to bind this into data grid view as,
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.
Book
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>>>()
.Select(x=>x.Value.Count).Max();
//Create the data table and for each table, add a column
var dataTable = new DataTable();
foreach (var key in dictionary.Keys)
{
dataTable.Columns.Add(key);
}
//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)
{
try
{
row[key] = dictionary[key][i];
}
catch
{
row[key] = null;
}
}
}
//Show data in grid
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = dataTable;
and here is the result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With