Using .NET 4 C#, I have a DataSet containing two DataTables generated from imported csv files, created from form registration data. One contains a record ID and a timestamp. The other is a list of product registrations (name, address, etc.), with the corresponding record ID (about 10,000 records)
How can I insert the timestamp from the first datatable into the second datatable matching the correct record ID? Can I attach a DataAdapter to existing DataSet and query against them that way? I was hoping I could add a timestamp column to me second datatable and update that from the first.
I know this doesn't make sense (why not include the timestamp when exporting the form data?). I'm using a Joomla form module for registrations, and the export does not include the timestamp. From the DB, I can export the timestamp and record ID data that matches, but the DataBase structure splits the record fields into separate tables, and I can't figure out how to merge the entire record back together into usable content, so I'm stuck with two csv's displaying data for the same record).
Any nudge in the right direction greatly appreciated.
You can of course just iterate all records yourself and match them up. But you can also set up a relationship between the DataTables in the dataset, then create a computed column in the records datatable that pulls a parent column's value. See this example: http://windowsdevcenter.com/dotnet/2003/05/26/datacolumn_expressions.html
See this article on how to actually add relationships: http://msdn.microsoft.com/en-us/library/ay82azad%28v=vs.71%29.aspx
Toward the bottom:
Parent.ColumnName Column in a parent table
So after you create the relationship, you'd do something like: ds["Table2"].Columns.Add("Timestamp", typeof(DateTime), "Parent.Timestamp")
Try this:
add new column to 2nd datatable
DataColumn dc = new DataColumn("DateCol", typeof(System.DateTime));
dt2.Columns.Add(dc);
Now update this datecol column in 2nd datatable using first datatable
dt2.AsEnumerable().Join( dt1.AsEnumerable(),
dt2Rows => dt2Rows.ItemArray["record_id"],
dt1Rows => dt1Rows.ItemArray["record_id"],
(dt2Rows, dt1Rows) => new { dt2Rows, dt1Rows })
.ToList()
.ForEach(i => i.dt2Rows.SetField("DateCol", i.dt1Rows.ItemArray["DateCol"]));
To use above linq query you have to Import the Systems.Linq namespace in your class file
Related
I have two hidden Datatables, one of which gets its data from a database, and the other from a static .csv file. I want to create a DataGridView with columns that has custom datatable expressions (just like a spreadsheet).
My question is: how do I formulate expressions in the datagridview to search for data in the other two tables?
Example: Table B has references for each product, a static unique id. Table A also have a reference to each product but also includes status for that product.
In the DataGridView I have three columns (ID, PRODUCT, STATUS). How can I write the expressions to fetch data from the other tables?
This is just how I think this can be solved, if you have another idea please let me know.
Thank you!
using Merge two tables
1- convert table1 to dataTable dtOne.
2- convert csv data to dataTable dtTwo.
3- dtAll = new Datatable();
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);
dataGridView.DataSource=dtAll;
I have a DataSet to which I need to add tables dynamically at runtime, but these tables need to reflect the existing database structures. Is there a way to pull the schema (not data) of a specific table into a DataSet at runtime.
So, for instance, I might have an Account table (along with hundreds of others) in a database. I need to create an Account table in the DataSet at runtime (based on various actions of the end users) but there are too many to manually code this for each table.
You didn't specify wich database engine you were working on, so the best generic method to do what you want to do would be to use IDataReader's GetSchemaTable method.
More info on how to do this here.
If you run a SQL query that returns a datatable, it will have the structure of the table. Thus,
select * from SourceTable where 1 = 2;
Which returns no rows, but all the columns. DataSet fill, etc. Done.
You can programatically modify and examine your data schema and data. You can add Columns programatically to the DataSet: http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx
DataTable workTable = new DataTable("Customers");
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
You can create new tables also into the DataSet. You can examine and traverse the schema of what you have: look at the Tables property of DataSet, it contains your DataTables (DataTableCollection). The DataTables contain Columns property. Knowing that it's straight forward.
This is what I am trying to achieve :
I have a table in a database in which there is a column named "item_code".
I need to query this table, returning ONE row at a time. Now, I need to use the value of the column "item_code" for the one row which has been returned to query ANOTHER table where I'll use it to fetch a bunch of row(s). How do I do this?
I tried using a datareader object in a while loop, fetch one row at a time and then query the other table inside this loop to fetch the rows required but I couldn't figure out how to put this data in a gridview (use datatable? if yes, how?) in such a way that the previous rows in the gridview don't get erased after each iteration of the while loop.
The only way I know for putting data into a gridview is by using .Fill() but obviously, Fill method wouldn't do in this case as it would wipe out the previous entries in the gridview.
Please help.
Your solution will work, but you are correct, Fill() will erase the contents of the table. Instead, use Merge()
var myMainTable = new DataTable();
foreach(var itemId in itemIds)
{
var currentTable = new DataTable();
// submit new query
myAdapter.Fill(currentTable)
myMainTable.Merge(currentTable);
}
I need to query this table, returning ONE row at a time. Now, I need to use the value of the column "item_code" for the one row which has been returned to query ANOTHER table where I'll use it to fetch a bunch of row(s). How do I do this?
You could use a single SQL query that joins the two tables on "item_code" and retrieves the results from the second table.
You can make it in SQL level in one step, like this:
SELECT Table2.*
FROM Table2
INNER JOIN Table1 ON Table1.item_code = Table2.item_code
ORDER BY Table2.item_code
And of course if you need to make a smaller list, you can wirte the WHERE too.
I'm trying to store a DataTable into a single column in a SQL Server table. The idea behind this is a user runs a SQL command and the returned output is stored into a datatable, then I want that datatable to be stored into a SQL Server logging table. Later on I want to be able to retrieve that entire datatable back for displaying on a logging aspx page.
Currently I'm just storing it as a big string but that doesn't give me column headers and the formatting is kinda funky as well as being inefficient.
TIA
I would probably convert the datatable to XML and store it into an XML field type if I was going to do what you are trying to do.
Hello you can try with WriteXml
this link give you sample interessant : http://msdn.microsoft.com/fr-fr/library/system.data.datatable.writexml.aspx
Another Idea is to create two tables in your database. It is slightly complex.
One Table contains two columns, Let name the table PTable.
Columns:
ID and ColumnID
ID is the primary key and ColumnID contains the name of your column in datatable
After creating this table create another table. It will consists of three fields. Let name it STable. This table stores the columns of you datatable.
Columns:
stblID, PtblID and PtColumnID
StbID is the primary key in this table, PtblID is the Primary key of PTable and PtColumnID is the ColumnID of PTable. This table stores the rows of table. Now store the data in this table and receive the data when you need it.
and the simplest idea is to create a table in your datbabase having an xml column and store your datatable as an xml.
I have one dataset in which there are
40 tables. Now I want to make a relation
between these tables and show
important data in grid. How do i do this?
If you're creating a typed dataset, it's easiest to create the relations in Visual Studio's dataset designer. Just right-click on the table in the designer, select Add->Relation, and specify the relation.
If you need to specify the relation in code, you can do it like this:
dataSet.Relations.Add(dataSet.Tables["Customers"].Columns["customerId"],
dataSet.Tables["Orders"].Columns["customerId"]);
Read all about it in MSDN here.
That is a large number of DataTables to have in a DataSet.
The first thing I would consider would be to reduce the number of DataTables (and eliminate the need for Relations) by populating the DataTables with queries that JOIN the database tables. For example, instead of having one DataTable for Product Category and another for Product Detail, it might be possible to combine the data for both database tables into one DataTable. Similarly, for Customer, Customer Address and Customer Phone, retrieve all of the data in one DataTable by using one query that does a JOIN on all three database tables.
Once you have minimized the number of DataTables in the DataSet, you can add Relations between DataTables if they have matching columns (even if the columns have different names). For example, there might be an Orders DataTable with a CustomerID column that matches the ID column in the Customers DataTable.
Here is the code to add a Relation to the DataSet for that situation. Assume that we have a DataSet dst containing two DataTables Customers and Orders.
DataColumn customerColumn, orderColumn;
customerColumn = dst.Tables["Customers"].Columns["ID"];
orderColumn = dst.Tables["Orders"].Columns["CustomerID"];
DataRelation dr = new DataRelation("CustomerOrders", customerColumn, orderColumn);
dst.Relations.Add(dr);
ds.Relations.Add("Products_Category",
ds.Tables("Categories").Columns("CategoryID"),
ds.Tables("Products").Columns("CategoryID"));
Did you try something like:
ds.Relations.Add("Products_Category",
ds.Tables("Categories").Columns("CategoryID"),
ds.Tables("Products").Columns("CategoryID"));
private void CreateRelation()
{
// Get the DataColumn objects from two DataTable objects
// in a DataSet. Code to get the DataSet not shown here.
DataColumn parentColumn =
DataSet1.Tables["Customers"].Columns["CustID"];
DataColumn childColumn =
DataSet1.Tables["Orders"].Columns["CustID"];
// Create DataRelation.
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders",
parentColumn, childColumn);
// Add the relation to the DataSet.
DataSet1.Relations.Add(relCustOrder);
}