Dynamically Create Datatable

Asked

Viewed 2,236 times

2

I need to create a DataTable Dynamic;

of the kind:

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 inside the for, how can I insert rows into the datable when these rows are not defined, the number of columns being dynamic?

1 answer

3


You can create a Datatable dynamically, but you must do it in 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.