How do I copy a column from one dataset into another?

anteplyPoenty

New Member
This function grabs a couple of field values from a dataset passed in, uses those to build an additional SQL query, then attempts to merge the fields from the dataset returned into the original dataset. This example uses dt as the source dataset for the additional data and ds as the recipient.Anyway, attempting to do this results in an error about the column already belonging to a dataset:\[code\]protected DataSet GetAdditionalFields(DataSet ds){ sqlObj = (Connections)Session["sqlObj"]; iFuncs = new iFunctions(sqlObj); string query, bn, sc; DataSet dt = new DataSet(); bn = ds.Tables[0].Rows[0]["cmt_branch"].ToString(); sc = ds.Tables[0].Rows[0]["cmt_stock_code"].ToString(); query = string.Format("SELECT SUM(cmt.cmt_quantity) AS cmt_all_qty, SUM(DECODE(cmt.cmt_branch, '{0}', cmt.cmt_quantity, NULL)) AS cmt_branch_qty FROM cmtmas cmt WHERE cmt.cmt_stock_code = '{1}'", bn, sc); dt = sqlObj.callMultiInformixQuery(query); foreach (DataColumn dc in dt.Tables[0].Columns) { ds.Tables[0].Columns.Add(dc.ColumnName, dc.DataType); ds.Tables[0].Rows[0][dc.ColumnName] = dt.Tables[0].Rows[0][dc.ColumnName]; } //Print_Data(ds); return ds; }\[/code\]This SEEMED to work fine because at first I did not have Print_Data(ds) commented out. When it's active in the code, after adding the two columns from dt into ds, I get a printout xls that has all the data correctly merged. If I comment out Print_Data(ds), the error about cmt_all_qty already existing in another table returns. Here is Print_Data just for reference, but it doesn't return anything so I'm not sure why it would make a difference in whether the above function works:\[code\] protected void Print_Data(DataSet dt) { string attachment = "attachment; filename=output.xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/vnd.ms-excel"; string tab = ""; foreach (DataColumn dc in dt.Tables[0].Columns) { Response.Write(tab + dc.ColumnName); tab = "\t"; } Response.Write("\n"); foreach (DataRow dr in dt.Tables[0].Rows) { tab = ""; for (int i = 0; i < dt.Tables[0].Columns.Count; i++) { Response.Write(tab + dr.ToString()); tab = "\t"; } Response.Write("\n"); } Response.End(); return; }\[/code\]This is the specific line that returns the error: \[code\]ds.Tables[0].Columns.Add(dc.ColumnName, dc.DataType);\[/code\]Any thoughts on this?
 
Back
Top