Combine 2 tables in same datset into 1 table - c#

Ok, I have searched and searched debugged guessed and tried hundreds of different ways.
I have an xml Style webresponse read into a dataset and am trying to display 3 of the 10 created tables of the dataset in a datagridview.
How does this get done?
I can display any 1 of the tables but how can i display more then one without any keys? Just matching the rows of each table to each other in numerical order?
StreamReader sreader = new StreamReader(rsp.GetResponseStream());
string rspXml = reader.ReadToEnd();
StringReader srxml = new StringReader(rspXml);
DataSet ds = new DataSet("Shipment");
ds.ReadXml(srxml);
dataGridView1.DataSource = ds;
dataGridView1.DataMember ="TotalCharges";
the three tables I need are "TotalCharges" "Shipment" and "Payments"

I think you should use DataSet.Merge() to create a new DataSet containing the data you want to display, then bind your dataGridView1 to that.

Related

C# - Add Empty Column to DataTable

I am creating an Excel using DataTable. My requirement is to skip first two columns and populate values from third column. When I try to add column with string.Empty, it creates Column1,Column2 in Excel.
As per link https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable , it auto generates Column1. But somehow I need to skip first two Columns.
Can someone help me to achieve this.
var myDataSet = new DataSet();
var table = myDataSet.Tables.Add("ProductDetails");
table.Columns.Add(string.Empty);
table.Columns.Add(string.Empty);
table.Columns.Add("ID");
table.Columns.Add("Name");
table.Columns.Add("Code");
table.Columns.Add("Price");
Current output in Excel:
Expected output:

C# How to create a Dataset instance with relations between two tables

Well thats my problem. I'm trying to query a remote postgresql DB and then fill TWO RELATED instanced tables with the result, so i can fill a form that displays information for both tables. Doing this with a single table was simple, but now i'm unable to correctly define relationships. I'm getting the “Object reference not set to an instance of an object” error What im doing wrong?
Relation is "components/provider_id" to "provider/id" so i can fill provider fields automatically in the components forms (while doing a search query).
Heres my code:
OdbcDataAdapter sdata = new OdbcDataAdapter(//Query string whatever);
OdbcDataAdapter sdata2 = new OdbcDataAdapter(//Query string whatever);
DataSet ds = new DataSet(); //new dataset instance
DataTable dtbl = new DataTable(); //two new instanced tables
DataTable dtbl2 = new DataTable();
sdata.Fill(dtbl); //fill both tables with each query data
sdata2.Fill(dtbl2);
ds.Tables.Add(dtbl); //Add those tables to DataSet
ds.Tables.Add(dtbl2);
//So now im tring to create a relation between both tables
// im getting "“Object reference not set to an instance of an object”
DataRelation dr = new DataRelation("provcomp",
ds.Tables["dtbl"].Columns["id"],
ds.Tables["dtbl2"].Columns["id_prov_comp"]);
Also I suppose that after that i will need some advice on creating some keys for the columns.
Can I get a little help? Please keep in mind that im fairly new to programing in general and c# in particular.
You should add the relation to Relations collection of your DataSet:
DataSet ds = new DataSet(); //new dataset instance
DataTable dtbl = new DataTable("Your Parent TableName"); //two new instanced tables
DataTable dtbl2 = new DataTable("Your Child TableName");
sdata.Fill(dtbl); //fill both tables with each query data
sdata2.Fill(dtbl2);
ds.Tables.Add(dtbl); //Add those tables to DataSet
ds.Tables.Add(dtbl2);
ds.Relations.Add("Your Relation Name",dtbl.Columns["id"], dtbl2.Columns["id_prov_comp"]);
//or
//ds.Relations.Add(ds.Tables["dtbl"].Columns["id"], ds.Tables["dtbl2"].Columns["id_prov_comp"]);
ds.AcceptChanges();

how to add new datatable to dataset at first position

i have one dataset with 3 data tables again i have to add one more data table in same dataset at first position(Ex:mydataset.tables[0]th position) .can any one help me regarding this.
You will probably need to pull all the datatables out of the dataset into a list, get them in the right order, and then re-add them all to the dataset since you cannot insert to or modify the existing order:
var tables = new DataTable[4];
tables[0] = mynewtable;
tables[1] = mydataset.Tables[0];
tables[2] = mydataset.Tables[1];
tables[3] = mydataset.Tables[2];
mydataset.Tables.Clear();
mydataset.Tables.Add(Tables[0]);
mydataset.Tables.Add(Tables[1]);
mydataset.Tables.Add(Tables[2]);
mydataset.Tables.Add(Tables[3]);

How can I divide a dataset equally into two parts?

I'm programming on Asp.net and C#.
I have a Dataset which is populated by records from database.
On my design page, I have two Datagrids.
How can I equally divide the records inside the Dataset so they can be bound to two separate datagrids?
you can use DataView on your dataset and then bind your 2 Datagrids on dataview
here a sample
http://www.dotnetperls.com/dataview
work for instance to set one dataview on rows.count/2 and the other too
This works for me,
var d=ds.Tables[0];// here ds is your dataset.
int count=d.Rows.Count;
var x=new DataTable();
for(int i=0;i<=count;i++)
{
var dr=d.Rows[i];
x.Rows.Add(dr.ItemArray);
d.Rows.RemoveAt(i);
}
var ret=new DataSet();
ret.Tables.Add(x);
ret.Tables.Add(d);
so now you have dataset that contain two equal datatable.

.Net C# DataTables and DataSets, How to relate tables

How do you take a couple of data tables and put them in a dataset and relate (that doesn't even sound like correct English) them?
I know how to create datatables.
Here is an example from one of my classes
// create the relationship between Booking and Booking_MNI
DataRelation relBookingMNI;
relBookingMNI = new DataRelation("BookingToBookingMNI",dsBooking.Tables["Booking"].Columns["Record_Id"],dsBooking.Tables["Booking_MNI"].Columns["booking_record_id"]);
dsBooking.Relations.Add(relBookingMNI);
dsBooking is my main dataset that contains 2 tables Booking and Booking_MNI
Where the Record_Id is the primary key and booking_record_id is the foreign key
I changed the code below to match my first example. But I think this is what you are looking for. In our production code this will produce the plus "+" symbol to the left of the row which would allow you to drill into the related table. Again I took production code and made it look like the first example so I don't know if it will compile but it should get you going in the right direction.
DataTable dtBooking = ds.Tables[0];
DataTable dtBooking_MNI = ds.Tables[1];
dtBooking.PrimaryKey = new DataColumn[] {dtBooking.Columns["Record_Id"]};
dtBooking_MNI.PrimaryKey = new DataColumn[] {dtBooking_MNI.Columns["booking_Record_Id"]};
/* Setup DataRelation between the DataTables */
DataColumn[] dcBookingColsArray = new DataColumn[1] {dtBooking.Columns["Record_Id"]};
DataColumn[] dcBookingMNIColsArray = new DataColumn[1] {dtBooking_MNI.Columns["booking_record_Id"]};
DataRelation relBooking_To_MNI = new DataRelation("Booking_To_MNI",dcBookingColsArray,dcBookingMNIColsArray);
ds.Relations.Add(relBooking_To_MNI_Units);
// grid where you want to display the relationship
grdBooking.DataSource = ds;
Look at the DataRelation class. It is what is used in a DataSet to relate two DataTables together.
Let's say you've got your DataTables named "orders" and "orderDetails". You want to create a relationship between them by their OrderNumber columns. We'll assume that orders is the parent and orderDetails is the child. We want to loop through the orders and then print each one's related sub-totals.
DataSet orderData = new DataSet("OrderData");
orderData.Tables.Add(orders);
orderData.Tables.Add(orderDetails);
orderData.Relations.Add("Order_OrderDetails", orders.Columns["OrderNumber"], orderDetails.Columns["OrderNumber"]);
Now, when you want to use that relationship somewhere else in your code:
DataRelation orderRelation = orderData.Relations["Order_OrderDetails"];
foreach (DataRow order in orders.Rows)
{
Console.WriteLine("Subtotals for Order {0}:", order["OrderNumber"]);
foreach (DataRow orderDetail in order.GetChildRows(orderRelation))
{
Console.WriteLine("Order Line {0}: {1}", orderDetail["OrderLineNumber"], string.Format("{0:C}", orderDetail["Price"]));
}
}
try this here is two table 1. categories & 2. Products
string query = "SELECT * FROM Categories; SELECT * FROM Products";
SqlConnection con = new SqlConnection();
SqlDataAdapter da = new SqlDataAdapter(query,con);
DataSet ds = new DataSet();
da.Fill(ds, "CategoriesAndProducts"); //CategoriesAndProducts dataset
string s = ds.Tables[0].Rows[0]["Name"].ToString();
string s1 = ds.Tables[1].Rows[0]["Name"].ToString();
Console.WriteLine(s); //from categories [0][0] like Electronic
Console.WriteLine(s1); //from Products [0][0] like LG
Have you looked into LINQ?
http://msdn.microsoft.com/en-us/netframework/aa904594.aspx
Perhaps you're looking for an orm solution like Entity Framework, NHibernate or Linq to SQL?
Appologies if I've misunderstood the question.
If you use Visual Studio 2005 or later try the following:
Right-click your project and select "Add/NewItem...", then choose DataSet from the wizard, which will create you some xsd and open the dataset designer.
Now you can create multiple tables, add columns to each table and draw relations (foreign key, with/without cascading...) between those tables.
in the autogenerated [YourNewDataSet}.Designer.cs-file, you will find the source code for these relations.
Something like this:
this.relationFK_DataTable2_DataTable1 = new global::System.Data.DataRelation("FK_DataTable2_DataTable1", new global::System.Data.DataColumn[] {
this.tableDataTable2.asdfasColumn}, new global::System.Data.DataColumn[] {
this.tableDataTable1.asdfaColumn}, false);
As always you can strip quite some portion of this code, if you code by hand instead of using the designer.
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