add tables dynamically based on database schema - c#

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.

Related

DataTable expressions referencing to two different tables

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;

Updating DataTable column from another DataTable

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

Access tables in a DataSet using each table's name with C#

A stored procedure returns multiple tables, the result set is assigned to a DataSet. Can I access the tables in the DataSet with each table's name?
For eg.:-
DataSet ds = Select(despatch_Packing_ID);
The DataSet contains 4 tables.
I am imposed to access the tables as
DataTable dtSales = ds.Tables[0];
How can I access the DataTable as
DataTable dtSales = ds.Tables["Sales"]; // Sales is tables where from I get data
By default the table names generated by a DbDataAdapter will have the names "Table", "Table1", "Table2", ...
You can override this by specifying DataTableMappings.
For example:
DbDataAdapter adapter = ...
...
adapter.TableMappings.Add("Table", "Sales");
adapter.TableMappings.Add("Table1", "Customers");
...
adapter.Fill(myDataSet);
...
The problem is that a query in a stored procedure can span multiple tables and views or even simply return a single value.
How would the DataTable get its name then?
I suppose it doesn't work, because returned data may be produced from multiple joined tables. In such case there is no way to identify them by name. But I haven't checked myself, so it is just my guess.

Problems updating a data source with data adapter update

First off, I've only started working with databases and c# so I could be making a really stupid mistake here so apologies in advance. I'm connected to a SQL server express database and can read from it fine, however whenever I have updated my DataSet to add new columns and then try to update the data source it wont update successfully. Code below:
DataColumn newColumn;
SqlCommandBuilder cmdBuild = new SqlCommandBuilder(_myAdapt);
foreach (String s in myList)
{
newColumn = new DataColumn(s, System.Type.GetType("System.String"));
_myData.Tables["Table1"].Columns.Add(newColumn);
}
_myAdapt.Update(_myData, "Table1");
Anyone got any suggestions as to why this wont work? I've debugged it and the data set is definitely being updated with the new columns but I cant seem to update the data source.
Thanks for any responses.
Does that column exist in the database (and just not in your database), or are you trying to ALTER the table definition in the database using the dataset.
I don't believe the 2nd of the above is possible. Your dataset needs to have a column structure to match that of the database table that you're updating. You can however add as many rows as you like to the dataset and they will all INSERT to the database fine.
If you feel you have a need to add columns to your table at run-time I'd suggest revisiting your data-model. Where possible your column definitions should be be unchanging over time, to represent the main attributes of the data entities you're storing.

How to make relation between tables which are in same dataset?

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

Categories

Resources