Steve
Steve

Reputation: 1058

C# Adding a Datatable to a Datatable

I know that sounds really weird, but I am fairly new to C# and I am hoping you guys can help me out.

I am looping thru a DataTable, then excute a qry and get the the result into a DataTable.

Works OK for one record, but as soon as there are more records, only the last record is in the DT, which makes sense, I just do not know how to fix it. I need to have all the records in the DT.

Here is my code, any suggestions are welcome....

    DataTable dt = ml.getRegistration();
    DataTable dt2 = new DataTable();

    foreach (DataRow row in dt.Rows)
    {     
        dt2 = ml.getRegistrationExport(row["ID"]);

    }
    GridView1.DataSource = dt2;
    GridView1.DataBind();

Upvotes: 1

Views: 717

Answers (2)

Wade73
Wade73

Reputation: 4509

If ml.getRegistrationExport is returning a datatable, then it overwrites the data as you loop through the first datatable.. You need to use dt2.merge to add all the data to the datatable. HTH.

DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();

foreach (DataRow row in dt.Rows)
{

dt2.merge(ml.getRegistrationExport(row["ID"]));

}

GridView1.DataSource = dt2;
GridView1.DataBind();

Upvotes: 3

David Basarab
David Basarab

Reputation: 73301

One of the problems I see is each row you are looping through you are replace dt2. So if you have 5 rows, you will replace dt2 5 times and which ever row happen to be last would rule dt2.

I would re think this.

Are what you are trying to do is add a row to dt2 for each row in the original dt?

DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();

foreach (DataRow row in dt.Rows)
{
    DataRow newRow = dt2.NewRow();

    // What Does getRegistrationExport return?  
    // A row or series of rows or a new DT?  
    // Each would change solution
    newRow["SomeColumn"] = ml.getRegistrationExport(row["ID"]);

    dt2.Rows.Add(newRow);
}

GridView1.DataSource = dt2;
GridView1.DataBind();

Upvotes: 2

Related Questions