How to remove the merged datatable from the datatable using C#.Net? - c#

I have two datatables D1 and D2.
I merged the datatable D2 with D1 as follows:
D1.Merge(D2);
But now, I want to remove the DataTable D2 from the D1. How to achieve this?

This may not be the most beautiful solution, but you can consider adding a distinctive column to your tables. I set those values by hand, but for example if your datatables are filled from a SQL query, you can easily add that distinctive column in those queries and use them accordingly.
D1.Columns.Add("ORIGINAL_DATATABLE_NAME", typeof(int));
D2.Columns.Add("ORIGINAL_DATATABLE_NAME", typeof(int));
foreach(DataRow row in D1.Rows)
row["ORIGINAL_DATATABLE_NAME"] = 1;
foreach(DataRow row in D2.Rows)
row["ORIGINAL_DATATABLE_NAME"] = 2;
D1.Merge(D2);
DataRow[] rows = D1.Select("ORIGINAL_DATATABLE_NAME=1", "");
DataSet ds = new DataSet();
ds.Merge(rows, false, MissingSchemaAction.Add);
ds.Tables[0].Columns.Remove("ORIGINAL_DATATABLE_NAME");

Related

How to Create sub DataTable from an existing DataTable

I have a DataTable(dataTable1) that have 25-30 columns. I want to bind a DataGridView by creating a small DataTable (dataTable2) that will have few columns (may 5-10) from the existing DataTable.
So my main task is to create a DataTable with fewer columns from the existing one.
Here is the code what I have tried so for..
DataTable subDataTable()
{
DataTable smallTable=new DataTable();
smallTable =dataTable1;// dataTable1 is already filled with data
smallTable.Columns.Remove("Column2");
smallTable.Columns.Remove("Column5");
smallTable.Columns.Remove("Column6");
smallTable.Columns.Remove("Column13");
smallTable.Columns.Remove("Column16");
return smallTable;
}
Its working fine. But I'm looking if there any better way.
You can try to convert your DataTable to IEnumerable,and Select necessary fields with linq like this:
var myValues = dataTable1.AsEnumerable()
.Select(x => new { col1 = x["Column1"], col2 = x["Column2"]..});
dataGridView.DataSource = myValues;
Your code will not work because you all you do is assign a variable smallTable with reference to dataTable1 and you removing columns from your original table object
Linq is faster to write but here is what you want to do to understand your issue:
DataTable smallTable = dataTable1.Clone(); // Copy data structure
// Now you can remove your columns
smallTable.Columns.Remove("Column2");
......
foreach (var row in dataTable1.Rows) // iterate all rows
{
var newRow = smallTable.NewRow();
foreach (var col in smallTable.Columns) // and iterate only needed columns
{
newRow[col.ColumnName] = row[col.ColumnName];
}
}
This is pretty much what sugar-coated by Linq
DataView dv = new DataView(dataTable1);
DataTable smallTable = dv.ToTable(true, new string[] { "Column2", "Column5"...});
https://social.msdn.microsoft.com/Forums/en-US/ac2c7c95-66d6-4db6-a6fb-4dccd5fa701e/is-there-a-better-way-to-get-subtable-with-selected-columns-of-a-datatable?forum=adodotnetdataset
Tomer.

Copy Specific Dataset Columns to Datatable

i have a DataSet which reads xml data and it has almost 20 columns,
i need 5 columns from the DataSet .
i have tried at my level but not able to get the DataTable with the specific columns i need.
some codes which i tried are :
DataTable dt = new DataTable(); //dt is blank DataTable
DataSet ds = new DataSet(); //ds is existing DataSet which has single table in it
dt.Columns[0]=dst4.Tables[0].Columns[0];
dt.Columns.Add(dst4.Tables[0].Columns[0]);
ds.Tables.Add(dt)
dst4.Tables.Columns.Add(dt);
You could clone the table which creates an empty table with the same columns, then you can remove the redundant columns.Here is an example with named columns, you could also use the indices:
DataTable dt = ds.Tables[0].Clone();
var colToTake = new[] { "Col1", "Col3", "Col7", "Col15", "Col19" };
var colsToRemove = dt.Columns.Cast<DataColumn>()
.Where(c => !colToTake.Contains(c.ColumnName));
foreach (DataColumn colToRemove in colsToRemove)
dt.Columns.Remove(colToRemove);
say you have to copy columns "ColumnName1", "ColumnName2", "ColumnName3", "ColumnName4", "ColumnName5" to new DataTable
DataTable source = dst4.Tables[0];
DataTable dt = source.DefaultView.ToTable(false, "ColumnName1", "ColumnName2", "ColumnName3", "ColumnName4", "ColumnName5");

Joining Values Of Two Columns From DataTable

Joining Values Of Two Columns From DataTable
Two columns make it in one columns from datatable
my datatable is
TagNumber, LogNumber Combined
124 1 2
125 1 3
126 2 4
o/p:
TagNumber
124 ~1~2
125 ~1~3
126 ~2~4
combined column is merge from column0 and column1
i dont understand hw can i do please write sample of code
I dont have experience on linq .
I add column bt hw can i merge two columns in that one columns
I got answer:
For i As Integer = 0 To dstemp.Tables(0).Rows.Count - 1
dstemp.Tables(0).Rows(i)(0) = dstemp.Tables(0).Rows(i)("TagNumber") & "~" & dstemp.Tables(0).Rows(i)("LogNumber") & "~" & dstemp.Tables(0).Rows(i)("Combined")
next
Try doing it like this.
dtTwoItems.Columns.Add("Combined", typeof(string), "TagNumber+'/'+LogNumber");
Ok if you really want to do this then you have create a extra DataTable with Three Columns:
TagNumber, LogNumber Combined:
as below:
private DataTable CreateDataTableColumns()
{
DataTable dtThreeItems = new DataTable();
dtThreeItems.Columns.Add("TagNumber", typeof(String));
dtThreeItems.Columns.Add("LogNumber", typeof(String));
dtThreeItems.Columns.Add("Combined", typeof(String));
return dtThreeItems;
}
Now iterate the old datatable as below to get combined value:
foreach (DataRow dr in dtTwoItems.Rows)
{
row = dtThreeItems.NewRow();
row["TagNumber"] = dr["TagNumber"].ToString();
row["LogNumber"] = dr["LogNumber"].ToString();
row["Combined"] = dr["TagNumber"].ToString()+"/"+dr["LogNumber"].ToString() ;
dtThreeItems.Rows.Add(row);
}
Thats All
DataTable is like a container.
It is not proper to join tables.
I recommend you'd use linq.
Did you try to Add new Column to DataTable and then iterate through Each Row to put value by combining them?
EDIT: I Am not sure if Linq or Datatable query have some inbuilt feature to do this, but simple solution is what I tell. Or if you are filling your datatable from any SQL Query based database, then write a SQL that has third column with merged value using concat of columns.
Edit2:
foreach (Datarow r in myTable.Rows) {
r["Newcolumn"] = Convert.ToString(r["c1"]) + "/" + Convert.ToString(r["c2"]);
}

Adding data to a row in a Dataset?

I am trying to add data to a row in a dataset but the data is always on a new row?
I need the data to populate under its column. I need something like Ds.Tables[0].Rows[1].add("Item")
This is how i am inserting the data:
DataSet ds = new DataSet();
ds.Tables.Add("Properties");
//GPS
ds.Tables[0].Columns.Add(ArrayProperties[0].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[0].Value);
//Street Num and Name
ds.Tables[0].Columns.Add(ArrayProperties[3].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[3].Value);
//Suburb
ds.Tables[0].Columns.Add(ArrayProperties[6].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[6].Value);
//City
ds.Tables[0].Columns.Add(ArrayProperties[7].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[7].Value);
//Province
ds.Tables[0].Columns.Add(ArrayProperties[8].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[8].Value);
//Locality Map
ds.Tables[0].Columns.Add(ArrayProperties[9].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[9].Value);
//Property Type
ds.Tables[0].Columns.Add(ArrayProperties[10].FormMobiField);
ds.Tables[0].Rows.Add(ArrayProperties[10].Value);
Just get a new Row from the DataTable and then add that row to the table, Use DataTable.NewRow method
DataRow dr = ds.Tables[0].NewRow();
dr["Column1"] = "value";
dr["Column2"] = "value";
dr["Column3"] = "value";
ds.Tables[0].Rows.Add(dr);
You are adding row after adding each column, You may first create your data table's structure by adding all the columns and then you can get the new row using DataTable.NewRow() and later you can add that row to your data table. After adding all the columns you may also try:
ds.Tables[0].Rows.Add(ArrayProperties[0].Value,ArrayProperties[1].Value,ArrayProperties[2].Value,ArrayProperties[3].Value);
The columns collection of a Datatable regards the table structure. In your code you mix adding columns and populating fileds.
You should first create the structure (not tested and syntax errors can occur):
Dataset ds = new Dataset();
Datatable dt = new Datatable();
dt.columns.add(new Column.add(...));
...
dt.columns.add(new Column.add(...));
ds.Tables.add(dt);
And then:
Datarow r = ds.tables[0].NewRow();
r["column1"] = value1;
...
r["columnX"] = valueX;
ds.Tables[0].rows.add(r);
See this msdn article for more details.
Add the columns as you are adding. For populating rows, do the below.
foreach (DataRow row in ds.Tables[0]) // Loop over the rows.
{
row[ArrayProperties[i].FormMobiField]=ArrayProperties[0].Value;
i++;
}
If it doesn't work then let me know,

Selected columns from DataTable

How to get the Selected columns form the DataTable? For e.g my BaseTable has three columns, ColumnA, ColumnB and ColumnC. Now as part of intermediate operations, I need to retrieve all the rows only from the ColumnA. Is there any predefined formula just like DataTable.Select?
DataView.ToTable Method.
DataView view = new DataView(MyDataTable);
DataTable distinctValues = view.ToTable(true, "ColumnA");
Now you can select.
DataRow[] myRows = distinctValues.Select();
From this question: How to select distinct rows in a datatable and store into an array you can get the distinct values:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "ColumnA");
If you're dealing with a large DataTable and care about the performance, I would suggest something like the following in .NET 2.0. I'm assuming the type of the data you're displaying is a string so please change as necessary.
Dictionary<string,string> colA = new Dictionary<string,string>();
foreach (DataRow row in table.Rows) {
colA[(string)row["ColumnA"]] = "";
}
return colA.Keys;

Categories

Resources