Michael Tot Korsgaard Michael Tot Korsgaard - 16 days ago 11
C# Question

DataTable overwrites previous row

So I'm trying to add some rows to a

DataTable
but for some reason it seems to overwrite the previous row. How can I prevent this.

What I have so far is this piece of code:

DataTable table = new DataTable();

foreach (CallData data in p.ValueArray)
{
DataRow row = table.NewRow();
foreach (CallParm parm in data.Parm)
{
if (!table.Columns.Contains(parm.Name))
{
table.Columns.Add(parm.Name, typeof(string));
}
row[parm.Name] = parm.Value;
}
table.Rows.Add(row);
}


Data example:

{
ValueArray: [
{
Parm: [
{
Name: "ID",
Value: 1
},
{
Name: "ID",
Value: 2
},
{
Name: "ID",
Value: 4
}
]
}
]
}


Data result

"ID": 4


wanted result

"ID": 1
"ID": 2
"ID": 4


I've already checked that it runs through the loops as it should, no problem there. It's when we add the row the problem seems to happen

mww mww
Answer

You need add all values from Param, not only last. You can try like this

 DataTable table = new DataTable();

foreach (CallData data in p.ValueArray)
{
    DataRow row = table.NewRow();
    foreach (CallParm parm in data.Parm)
    {
        if (!table.Columns.Contains(parm.Name))
        {
            table.Columns.Add(parm.Name, typeof(string));
        }
        row[parm.Name] = parm.Value;
        //now you add all items in this loop not only last element.
        table.Rows.Add(row);
    }

}