You should add DataColumn
, DataRow
separately, the below method convert a List
collection to DataTable
based on a sample , Change the columns by your own problem.
static DataTable Convert(List<string[]> list)
{
DataTable table = new DataTable();
int columns = 0;
foreach (var array in list)
{
if (array.Length > columns)
{
columns = array.Length;
}
}
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
foreach (var array in list)
{
table.Rows.Add(array);
}
return table;
}
You can call that method by the following sample method:
static void sample()
{
List<string[]> list = new List<string[]>();
list.Add(new string[] { "Column 1", "Column 2", "Column 3" });
list.Add(new string[] { "Row 2", "Row 2" });
list.Add(new string[] { "Row 3" });
DataTable table = Convert(list);
dataGridView1.DataSource = table;
}