开发者

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.getRegist开发者_运维技巧rationExport(row["ID"]);

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


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();


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜