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:
I did a search and found some seemingly related answers, but they don't really do what I'm after.
Given a valid connection string and a table name, I want to get a DataTable of the table. I.e. if the table has a column called "Name", I want the DataTable set up so I can do dt["Name"] = "blah";
The trick is, I don't want to hard code any of that stuff, I want to do it dynamically.
People tell you to use SqlConnection.GetSchema, but that gives you back a table with a bunch of stuff in it.
Everybody has random tricks like TOP 0 * from the table and get the schema from there, etc.
But is there a way to get the table with the primary keys, unique indexes, etc. Ie.. in the final format to do a bulk insert.
You can use SqlDataAdapter.FillSchema:
var connection = #"Your connection string";
var command = "SELECT * FROM Table1";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();
dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
This way you will have an empty DataTable with columns and keys defined and ready to use in code like dataTable["Name"] = "blah";.
Greets! I am having problems importing a row I created into a DataTable that resides in a DataSet. I pre-populate the "newDataSet" from a SQL Database that is empty but it does contain Tables with a Schema already set up. I have verified that the DataTables in "newDataSet" are getting the Schema imported to them.
Everything looks right as there is no error logs, but no datarow is ever added. Both my Console.WriteLine report back the same Count.
Thank you for taking the time to review this. I appreciate you.
Initial Setup:
var DataSet newDataSet = new DataSet("foo"); // A SQL Adapater was used to fill this from a pre existing Database.
var checkDataSet = new DataSet();
var checkDataTable = new DataTable();
Cloning the DataSet and DataTable.
checkDataSet = newDataSet.Clone();
checkDataTable = checkDataSet.Tables["moreFoo"].Clone();
Creating the DataRow:
var newDataRow = checkDataTable.NewRow();
Filling the Columns in the DataRow:
newDataRow[0] = obj1;
newDataRow[1] = obj2;
newDataRow[2] = obj3;
Importing the DataRow to the "newDataSet" DataTable:
Console.WriteLine(newDataSet.Tables["moreFoo"].Rows.Count.ToString());
newDataSet.Tables["moreFoo"].ImportRow(newDataRow);
Console.WritelLine(newDataSet.Tables["moreFoo"].Rows.Count.ToString());
The answer is:
newDataSet.Tables["moreFoo"].ImportRow(newDataRow);
should be:
newDataSet.Tables["moreFoo"].Rows.Add(newDataRow.ItemArray);
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.
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);
}