How would I convert List<List<string>> to a DataTable? I am trying to set the DataSource of a gridview to a List<List<string>> variable.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This can easily be done using extension methods.
Add this class to your solution
static class ListExtensions
{
public static DataTable ToDataTable(this List<List<string>> list)
{
DataTable tmp = new DataTable();
foreach (List<string> row in list)
{
tmp.Rows.Add(row.ToArray());
}
return tmp;
}
}
then use the extension method like this:
List<List<string>> myList = new List<List<string>>(); // Fill with values... DataTable table = myList.ToDataTable();
Method 2
I would rather set DataSource of the grid to BindableList, which you would perhaps create easier, instead of double nested List, you would have List of Rows (where the Row is business entity represented, for example Customer).
Method 3
public static DataTable ToDataTable(this List<List<string>> list)
{
DataTable dt = new DataTable();
list.First().ForEach(colname => dt.Columns.Add(colname));
foreach (List<string> row in list.Skip(1))
dt.Rows.Add(row.ToArray());
return dt;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0