0

I have dictionaries with key value as follows Dic1(Name,Anu), Dic2(Age,22), Dic3(Name,Cas),Dic4(Age,25), Dic5(Sex,Male) . I want to create a data table with Name, Age and Sex as Column header and mapped with corresponding Values as the row data.

Name Age Sex Anu 22 null Cas 25 Male

Anu
  • 15
  • 1
  • 4

1 Answers1

1

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;
}
Siavash
  • 2,813
  • 4
  • 29
  • 42