Create DataTable Dynamically

2

I need to create a dynamic DataTable

of the genre:

List<p> =...
List<l>=....

DataTable dt = new DataTable();
foreach (Prod pr in p)
{
    dt.Columns.Add(prod.Nome.Trim());
    for (int i = 0; i < l.Count; i++)
    {
        dt.Rows.Add(GetDados(pr,l[i]),GetDados(pr,l[i])...);
    }
}

My problem is within for , how can I insert rows into the datable, when those rows are not defined, and the number of columns is dynamic?

    
asked by anonymous 17.04.2014 / 17:08

1 answer

3

You can dynamically create a DataTable, but you must do it by parts. First define the columns and then insert rows according to the columns, for example:

DataTable dt = new DataTable();

// defina as colunas da DataTable
foreach (Prod pr in p)
    dt.Columns.Add(pr.Nome.Trim());

// insira linhas
for (int i = 0; i < l.Count; i++)
{
    DataRow row = dt.NewRow();
    foreach (Prod pr in p)  
    {
        row[pr.Nome.Trim()] = GetDados(pr,l[i]);
    }
    dt.Rows.Add(row);
}

Note: Your code is not 100%, but I believe the path is there

    
17.04.2014 / 17:21