I'm working on a C# 4.0 WinForms application, with SQL Server 2012 Express.
I need to combine the data from 2-tables into a single DataTable. I've tried using the 2-suggestions found below, in creating a DataSet, passing 2-queries to a SqlDataAdapter and then filling the DataSet.
How to fill Dataset with multiple tables?
Merge 2 DataTables and store in a new one
I've created 2-DataTables, i.e. dt1 and dt2, assigning the first table "Table" to the DataTable dt1. I've assigned the 2nd table "Table1" to the next DataTable,i.e. dt2. I created a 3rd DataTable dtAll and attempted to merge the tables, as shown below.
//Other variables not shown
string dateIN = "";
string dateOUT = "";
DataSet ds = new DataSet();
//SqlConnection here
conn.Open();
SqlDataAdapter adap = new SqlDataAdapter(
"SELECT * FROM AssignmentsIN WHERE ScheduledDateIN BETWEEN @start AND @end ORDER BY ScheduledDateIN ASC; SELECT * FROM AssignmentsOUT WHERE ScheduledDateOUT BETWEEN @start AND @end ORDER BY ScheduledDateOUT ASC", conn);
adap.SelectCommand.Parameters.Add("@start", SqlDbType.NVarChar).Value = dStart;
adap.SelectCommand.Parameters.Add("@end", SqlDbType.NVarChar).Value = dEnd;
adap.TableMappings.Add("Table", "AssignmentsIN");
adap.TableMappings.Add("Table1", "AssignmentsOUT");
adap.Fill(ds);
DataTable dt1 = ds.Tables["AssignmentsIN"];
DataTable dt2 = ds.Tables["AssignmentsOUT"];
DataTable dtAll;
dtAll = dt1.Copy();
dtAll.Merge(dt2);
foreach (DataRow row in dtAll.Rows)
{
dateIN = row.Field<string>("ScheduledDateIN").Trim();//The data here shows up!
//Data from 1st table shows up correctly.
dateOUT = row.Field<string>("ScheduledDateOUT").Trim();
//^^ This begins the line where it throws the exception ^^
//However, when the code attempts to access data from the 2nd table it errors.
}
The problem I'm running into, is that when my code gets to the place where I'm trying to access the data which resides in dt2, it throws the exception "Object reference not set to an instance of an object."
Both DateIN and DateOUT are fields of type string, not DateTime. As stated below, I can actually "See" data from the 2nd table, if I look into the DataSet. It shows up in a row.ItemArray. My question remains, how to successfully Merge those 2-tables into one DataTable. dtAll has the data from the 1st table. How can I get the data from dt2 into dtAll?
I can see the data from the 2nd table if I drill-down into the DataSet ds. How can I populate both DataTables, i.e. dt1 & dt2 and merge them into dtAll and successfully access data from the 2nd table?
UPDATE: After researching further on datatable merges; because the 2-database tables have dissimilar data structures, I've realized that attempting to Merge them into one DataTable may be impractical. Therefore, I am closing out this question without a resolution. I appreciate the responses I have rec'd.