How to combine two DataSet Tables into one - c#

I am attempting to do as stated above combing two DataSet.tables into one table. I was wondering if it were possible to do so. I call my stored procedure and it returns my values I set them to a table. (All illustrated below).
Tried:
Adding both table names in the Mapping section ("Tables", IncomingProductTotals).
Adding both as one table in Mapping Section ("Tables", IncomingProductTotals1) ("Tables", TotalDownTimeResults1)
Doing lots of research most I can find is on sql joining tables.
SqlCommand cmd = new SqlCommand("L_GetTimeTotals", conn);
cmd.Parameters.Add("#startTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker2.SelectedDate;
cmd.Parameters.Add("#endTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker3.SelectedDate;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
var ds = new DataSet();
ds.Tables.Add("IncomingProductTotals");
ds.Tables.Add("IncomingProductTotalsA");
ds.Tables.Add("IncomingProductTotalsB");
ds.Tables.Add("IncomingProductTotals1");
ds.Tables.Add("IncomingProductTotalsA1");
ds.Tables.Add("IncomingProductTotalsB1");
da.TableMappings.Add("Table", "IncomingProductTotals");
da.TableMappings.Add("Table1", "IncomingProductTotalsA");
da.TableMappings.Add("Table2", "IncomingProductTotalsB");
da.TableMappings.Add("Table3", "IncomingProductTotals1");
da.TableMappings.Add("Table4", "IncomingProductTotalsA1");
da.TableMappings.Add("Table5", "IncomingProductTotalsB1");
da.Fill(ds);
ds.Tables.Remove("IncomingProductTotalsA");
ds.Tables.Remove("IncomingProductTotalsB");
ds.Tables.Remove("IncomingProductTotalsA1");
ds.Tables.Remove("IncomingProductTotalsB1");
ExcelHelper.ToExcel(ds, "TimeTotals.xls", Page.Response);

Have you tried the Merge method? http://msdn.microsoft.com/en-us/library/system.data.datatable.merge(v=vs.110).aspx
foreach(var t in ds.Tables.Skip(1))
{
t.Merge(ds.Tables[0]);
}
edit:
Skip is Linq. You can use this too:
for(int i = 1; i < ds.Tables.Count - 1; i++)
ds.Tables[i].Merge(ds.Tables[0]);

Related

mysql selecting with join to dataset and datatable in c#

I searched a lot but could not find the right solution.
Lets say ill select data like:
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[...]; //<== here is the problem
}
and I want to add this to a datatable,
How do I call the table in this case ?
Is it tableA ?
Does it matters how I name it ? (could I name it foobar as well???)
It is unclear what you are really asking for, but due to the length of comment and clarification, putting into an answer.
If you are trying to get multiple query results back from MySQL into a single "DataSet" (which can contain multiple tables), your query could contain multiple sql-statements and each would be returned into the dataset for you as different table results. For example, if you did something like...
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText =
#"select * from TableA;
select * from TableB;
SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
Your dataset would have 3 tables in it in direct correlation of the queries provided..
ds.Tables[0] = result of tableA all records.
ds.Tables[1] = result of tableB all records.
ds.Tables[2] = result of JOIN query tableA and tableB.
you could then refer to them locally however you need to...
ds.Tables[0].TableName = "anyLocalTableNameReference".
var t1Recs = ds.Tables[0].Rows.Count;
etc... or even create your own individual datatable variable name without having to explicitly reference the dataset and table array reference
DataTable myLocalTableA = ds.Tables[0];
DataTable myLocalTableB = ds.Tables[1];
DataTable myJoinResult = ds.Tables[2];
Hopefully this clarifies a bunch with the querying and referencing of multiple data results returned and how to then reference to the tables individually.

How to arrange the FieldName in AspxGridView?

I want to arrange the Field Names as user wants to display. I am not using SqlDataSource. I am calling the stored procedure by programming like below.
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalSalesQuantity",con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateFrom", DateFromStr);
cmd.Parameters.AddWithValue("#DateTo", DateToStr);
//cmd.Parameters.AddWithValue("#DateFrom", "2015-01-01 00:00:00");
//cmd.Parameters.AddWithValue("#DateTo", "2015-12-31 23:59:59");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
In result, I can see the field name how i have given the Column_name in my query. But, User wants to see the Field Name how they are arranging.
For Example:
select
student_id,student_name ,Class,School_Name
From
Student_Details
If above one is my stored procedure. I will get the Field Name how I mentioned in my query.
But User wants to see the result how they are giving. If user give School_Name,Class,Student_id,School_Name.
Is there anyway to arrange in AspxGridView?
Check my answer Based on my understanding of the question and #mohamed's comment.
Try to use the DataColumn.SetOrdinal method. For example:
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ds.Tables[0].Columns["School_Name"].SetOrdinal(0);
ds.Tables[0].Columns["Class"].SetOrdinal(1);
ds.Tables[0].Columns["Student_id"].SetOrdinal(2);
ds.Tables[0].Columns["School_Name"].SetOrdinal(3);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
even if user changes the select statement order of columns will not change.
Use the hiddentext field and get the column names as user wants to display in which order.
string selectedColumns = HiddentxtSelectedColumn.Value;
Move the selectedColumns to array
string[] names = selectedColumns.Split(',');
sda.Fill(ds);
for (int i = 0; i < names.Length; i++)
{
ds.Tables[0].Columns[names[i]].SetOrdinal(i);`
}
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
Now It will run exactly.

A chart element with the name 'John' already exists in the 'SeriesCollection'

I am following this post, to build a bar chart and show on my webpage. Below is the code i have done to accomplish it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from ForChart";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet, "Query");
foreach (DataRow row in myDataSet.Tables["Query"].Rows)
{
string seriesName = row["SalesRep"].ToString();
Chart1.Series.Add(seriesName);
Chart1.Series[seriesName].ChartType = SeriesChartType.Line;
Chart1.Series[seriesName].BorderWidth = 2;
for (int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)
{
string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;
string YVal = Convert.ToString(row[columnName]);
Chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
}
GridView1.DataSource = myDataSet;
GridView1.DataBind();
cmd.Connection.Close();
And my table is having the below data. Please check the snapshot
But when i run the code i am getting the below error. Please help me to resolve the issue:
A chart element with the name 'John' already exists in the 'SeriesCollection'.
I am not able to traverse the records thats why i am getting this error, but i don't know how to traverse through all the records.
Coding help would be very much appreciated. Thanks.
I'm assuming that Chart1.Series requires unique names, and thus this call will fail when you try to enter the same name multiple times:
Chart1.Series.Add(seriesName);
Ugh, that entire example on MSDN is filled with bad practices:
select *
no usings used with SqlConnection, SqlCommand,...
mixing UI code and DB code (they should be in separate classes)
Look at this example for a possible solution.

How do I use adapter.Update(table)

string qry="select *from mom";
Dataset dataset= new Dataset();
SqlDataAdapteradap adap= new SqlDataAdapter(qry,con);
adap.Fill(dataset,"MOM");
DataRow drow = dataset.Tables["MOM"].NewRow();
drow[0] = MRefDDL.SelectedItem.Text;
drow[1] = project.Text.Trim();
drow[2] = agendatopic3.Text.Trim();
drow[3] = presenter3.Text.Trim();
drow[4] = discus.Text.Trim();
drow[5] = conclu.Text.Trim();
drow[6] = "1";
dataset.Tables["MOM"].Rows.Add(drow);
adap = new SqlDataAdapter();
adap.Update(dataset, "MOM");
Here I have One Dataset with MOM Table which fill by data adapter
when after add new row into data set. iwant add this row into database
table with help of adapter.update() Method.But its giving me error:-
Update requires a valid InsertCommand when passed DataRow collection
with new rows.
In the dataadapter, there are insert, update and delete queries that you need to add. The wizard can also do that for you. You can also:
adp.InsertCommand = New SqlCommand(sql, connection)
etc.
Look at https://stackoverflow.com/a/21239695/1662973 for more detailed info.
you are reinitializing the dataadapter just before the Update() method. Please comment this.
//adap = new SqlDataAdapter(); // make this line comment
adap.Update(dataset, "MOM");

Using SqlDataAdapter to insert a row

I want to insert a row into the Database using SqlDataAdapter. I've 2 tables (Custormers & Orders) in CustomerOrders database and has more than thousand records. I want to create a GUI (TextBoxes) for adding new customer & orders into the Database to their respective tables.
How should I do it?
I guess the method that is usually followed is
dataAdapter = new SqlDataAdapter (sqlQuery, conn);
dataSet = new DataSet();
da.Fill(dataSet);
Now take the values from textboxes (or use DataBinding) to add a new row into the dataSet and call
da.Update(dataSet);
But the Question is Why should I fetch all other records into dataSet using da.Fill(dataSet ) in the first place? I just want to add a single new record.
For this purpose what I'm doing is, Creating the schema of the Database in the DataSet. like this:
DataSet customerOrders = new DataSet("CustomerOrders");
DataTable customers = customerOrders.Tables.Add("Customers");
DataTable orders = customerOrders.Tables.Add("Orders");
customers.Columns.Add("CustomerID", Type.GetType("System.Int32"));
customers.Columns.Add("FirstName", Type.GetType("System.String"));
customers.Columns.Add("LastName", Type.GetType("System.String"));
customers.Columns.Add("Phone", Type.GetType("System.String"));
customers.Columns.Add("Email", Type.GetType("System.String"));
orders.Columns.Add("CustomerID", Type.GetType("System.Int32"));
orders.Columns.Add("OrderID", Type.GetType("System.Int32"));
orders.Columns.Add("OrderAmount", Type.GetType("System.Double"));
orders.Columns.Add("OrderDate", Type.GetType("System.DateTime"));
customerOrders.Relations.Add("Cust_Order_Rel", customerOrders.Tables["Customers"].Columns["CustomerID"], customerOrders.Tables["Orders"].Columns["CustomerID"]);
I used DataBinding to bind these columns to respective text boxes.
Now I'm confused! What should I do next? How to use Insert command? Because I didn't give any dataAdapter.SelectCommand so dataAdapter.Update() wont work I guess. Please suggest a correct approach.
Set the select command with a "0 = 1" filter and use an SqlCommandBuilder so that the insert command is automatically generated for you.
var sqlQuery = "select * from Customers where 0 = 1";
dataAdapter = new SqlDataAdapter(sqlQuery, conn);
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
var newRow = dataSet.Tables["Customers"].NewRow();
newRow["CustomerID"] = 55;
dataSet.Tables["Customers"].Rows.Add(newRow);
new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataSet);
You can fill the dataSet with an empty set e.g.:
da = new SqlDataAdapter ("SELECT * FROM Customers WHERE id = -1", conn);
dataSet = new DataSet();
da.Fill(dataSet);
Then you add your rows and call update.
For this scenario though it would probably be better not to use SqlDataAdapter. Instead use the SqlCommand object directly for insertion. (Even better, use LINQ to SQL or any other ORM)
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True");
SqlDataAdapter da=new SqlDataAdapter("Insert Into Employee values("+textBox1.Text+",'"+textBox2.Text+"','"+textBox3.Text+"',"+textBox4.Text+")",con);
DataSet ds = new DataSet();
da.Fill(ds);
I have to do first time. You can try it . It works well.

Categories