We have two columns in a DataTable, like so:
COL1 COL2
Abc 5
Def 8
Ghi 3
We're trying to sort this datatable based on COL2 in decreasing order.
COL1 COL2
ghi 8
abc 4
def 3
jkl 1
We tried this:
ft.DefaultView.Sort = "COL2 desc";
ft = ft.DefaultView.ToTable(true);
but, without using a DataView, we want to sort the DataTable itself, not the DataView.
I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.
What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:
DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();
This will help you...
DataTable dt = new DataTable();
dt.DefaultView.Sort = "Column_name desc";
dt = dt.DefaultView.ToTable();
Its Simple Use .Select function.
DataRow[] foundRows=table.Select("Date = '1/31/1979' or OrderID = 2", "CompanyName ASC");
DataTable dt = foundRows.CopyToDataTable();
And it's done......Happy Coding
Maybe the following can help:
DataRow[] dataRows = table.Select().OrderBy(u => u["EmailId"]).ToArray();
Here, you can use other Lambda expression queries too.
Or, if you can use a DataGridView, you could just call Sort(column, direction):
namespace Sorter
{
using System;
using System.ComponentModel;
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.Rows.Add("Abc", 5);
this.dataGridView1.Rows.Add("Def", 8);
this.dataGridView1.Rows.Add("Ghi", 3);
this.dataGridView1.Sort(this.dataGridView1.Columns[1],
ListSortDirection.Ascending);
}
}
}
Which would give you the desired result:
Did you try using the Select(filterExpression, sortOrder) method on DataTable? See here for an example. Note this method will not sort the data table in place, if that is what you are looking for, but it will return a sorted array of rows without using a data view.
table.DefaultView.Sort = "[occr] DESC";
Use LINQ - The beauty of C#
DataTable newDataTable = baseTable.AsEnumerable()
.OrderBy(r=> r.Field<int>("ColumnName"))
.CopyToDataTable();
There is 2 way for sort data
1) sorting just data and fill into grid:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
DataTable dt2 = new DataTable(); // temp data table
DataRow[] dra = dt1.Select("", "ID DESC");
if (dra.Length > 0)
dt2 = dra.CopyToDataTable();
datagridview1.DataSource = dt2;
2) sort default view that is like of sort with grid column header:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
dt1.DefaultView.Sort = "ID DESC";
datagridview1.DataSource = dt1;
It turns out there is a special case where this can be achieved. The trick is when building the DataTable, collect all the rows in a list, sort them, then add them. This case just came up here.
//Hope This will help you..
DataTable table = new DataTable();
//DataRow[] rowArray = dataTable.Select();
table = dataTable.Clone();
for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
{
table.ImportRow(dataTable.Rows[i]);
}
return table;
TL;DR
use tableObject.Select(queryExpression, sortOrderExpression) to select data in sorted manner
Complete example
Complete working example - can be tested in a console application:
using System;
using System.Data;
namespace A
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable("Orders");
table.Columns.Add("OrderID", typeof(Int32));
table.Columns.Add("OrderQuantity", typeof(Int32));
table.Columns.Add("CompanyName", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
DataRow newRow = table.NewRow();
newRow["OrderID"] = 1;
newRow["OrderQuantity"] = 3;
newRow["CompanyName"] = "NewCompanyName";
newRow["Date"] = "1979, 1, 31";
// Add the row to the rows collection.
table.Rows.Add(newRow);
DataRow newRow2 = table.NewRow();
newRow2["OrderID"] = 2;
newRow2["OrderQuantity"] = 2;
newRow2["CompanyName"] = "NewCompanyName1";
table.Rows.Add(newRow2);
DataRow newRow3 = table.NewRow();
newRow3["OrderID"] = 3;
newRow3["OrderQuantity"] = 2;
newRow3["CompanyName"] = "NewCompanyName2";
table.Rows.Add(newRow3);
DataRow[] foundRows;
Console.WriteLine("Original table's CompanyNames");
Console.WriteLine("************************************");
foundRows = table.Select();
// Print column 0 of each returned row.
for (int i = 0; i < foundRows.Length; i++)
Console.WriteLine(foundRows[i][2]);
// Presuming the DataTable has a column named Date.
string expression = "Date = '1/31/1979' or OrderID = 2";
// string expression = "OrderQuantity = 2 and OrderID = 2";
// Sort descending by column named CompanyName.
string sortOrder = "CompanyName ASC";
Console.WriteLine("\nCompanyNames data for Date = '1/31/1979' or OrderID = 2, sorted CompanyName ASC");
Console.WriteLine("************************************");
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression, sortOrder);
// Print column 0 of each returned row.
for (int i = 0; i < foundRows.Length; i++)
Console.WriteLine(foundRows[i][2]);
Console.ReadKey();
}
}
}
Output
try this:
DataTable DT = new DataTable();
DataTable sortedDT = DT;
sortedDT.Clear();
foreach (DataRow row in DT.Select("", "DiffTotal desc"))
{
sortedDT.NewRow();
sortedDT.Rows.Add(row);
}
DT = sortedDT;
Yes the above answers describing the corect way to sort datatable
DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();
But in addition to this, to select particular row in it you can use LINQ and try following
var Temp = MyDataSet.Tables[0].AsEnumerable().Take(1).CopyToDataTable();
Related
I'm trying to sort the data in a DataTable which is in a Dataset.
By Using the below code it is working
DataTable dt = (this._dataSet).Tables["Customers"];
dt.DefaultView.Sort = "Surname";
dt.TableName = "Customers";
DataTable defaultviewtable = dt.DefaultView.ToTable();
(this._dataSet).Tables.Remove("Customers");
(this._dataSet).Tables.Add(defaultviewtable);
By using the above code sorting is working, but because of the other table relationships it's not removing the table (from the line 5 in code) and throwing an error "Relationships should be removed first" which is not at all my case. If I remove the relationships I will loose the data from other table.
I tried by Using "DataviewManager" for sorting but it is not sorting ?
Can any one suggest how to append the sorted data to DataSet from DataViewManager ?
Note : My Dataset has 4 tables.
This is the code :
var dataViewSetting = new DataViewManager(this._dataSet).DataViewSettings["Customers"];
if (dataViewSetting != null)
{
dataViewSetting.ApplyDefaultSort = true;
dataViewSetting.Sort = "Surname";
}
DataTable dt = (this._dataSet).Tables["Customers"];
dt.DefaultView.Sort = "Surname";
dt.TableName = "Customers";
DataTable defaultviewtable = dt.DefaultView.ToTable();
// Remove all rows from the table
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
dt.Rows[i].Delete();
}
// Add rows back using the sorted view
for(int i = 0; i < defaultviewtable.Rows.Count; i++)
{
dt.Rows.Add(defaultviewtable.Rows[i].ItemArray);
}
This question already has answers here:
how to join two datatable datas into one datatable to show in one gridview in asp.net
(4 answers)
Closed 9 years ago.
I have two identical DataTables from two different databases (but the ids are unique!). So now I want to have combine this data into a single DataTable. I have no idea what to do.
I tried the following:
DataTable one = new DataTable();
one = baza_win.pobierz_dane("SELECT...");
DataTable two = new DataTable();
two = baza_win2.pobierz_dane("SELECT...");
//DataTable sum = one + two;
DataTable sum = new DataTable();
sum.Clone(one);
sum.Merge(two,false);
But this doesn't work at sum.Clone(one);
Any ideas?
sum = one.Copy();
sum.Merge(two);
I think you need Copy instead of Clone:
DataTable one = new DataTable();
one = baza_win.pobierz_dane("SELECT...");
DataTable two = new DataTable();
two = baza_win2.pobierz_dane("SELECT...");
//DataTable sum = one + two;
DataTable sum = new DataTable();
sum.Copy(one);
sum.Merge(two,false);
copied from link
http://msdn.microsoft.com/en-us/library/fk68ew7b.aspx
duplicate of
how to join two datatable datas into one datatable to show in one gridview in asp.net
private static void DemonstrateMergeTable()
{
DataTable table1 = new DataTable("Items");
// Add columns
DataColumn column1 = new DataColumn("id", typeof(System.Int32));
DataColumn column2 = new DataColumn("item", typeof(System.Int32));
table1.Columns.Add(column1);
table1.Columns.Add(column2);
// Set the primary key column.
table1.PrimaryKey = new DataColumn[] { column1 };
// Add RowChanged event handler for the table.
table1.RowChanged +=
new System.Data.DataRowChangeEventHandler(Row_Changed);
// Add some rows.
DataRow row;
for (int i = 0; i <= 3; i++)
{
row = table1.NewRow();
row["id"] = i;
row["item"] = i;
table1.Rows.Add(row);
}
// Accept changes.
table1.AcceptChanges();
PrintValues(table1, "Original values");
// Create a second DataTable identical to the first.
DataTable table2 = table1.Clone();
// Add three rows. Note that the id column can't be the
// same as existing rows in the original table.
row = table2.NewRow();
row["id"] = 14;
row["item"] = 774;
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 12;
row["item"] = 555;
table2.Rows.Add(row);
row = table2.NewRow();
row["id"] = 13;
row["item"] = 665;
table2.Rows.Add(row);
// Merge table2 into the table1.
Console.WriteLine("Merging");
table1.Merge(table2);
PrintValues(table1, "Merged With table1");
}
private static void Row_Changed(object sender,
DataRowChangeEventArgs e)
{
Console.WriteLine("Row changed {0}\t{1}",
e.Action, e.Row.ItemArray[0]);
}
private static void PrintValues(DataTable table, string label)
{
// Display the values in the supplied DataTable:
Console.WriteLine(label);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
Console.Write("\t " + row[col].ToString());
}
Console.WriteLine();
}
}
try the following... CLONE the first table so it has proper structure, THEN merge two into it.
DataTable sum = one.Clone()
sum.Merge(two,false);
is there any way to replace all occurrences of a value in a data table with another value from a different data table.for example I have two data table one has Itemid and another has itemid and item name.I need to replace item id in first data table with the item name from the second data table..Is there any possible way to replace all occurances at one go or should i go for the usual loop method and use Datatable.Select method.Please help.Thanks in advance.
What about this? (I realise it is a loop - but very compact and any built in method would loop anyway, just behind the scenes)
//Build first Test DT
DataTable dt1 = new DataTable();
dt1.Columns.Add("itemID", typeof(string));
//Build Second Test DT
DataTable dt2 = new DataTable();
dt2.Columns.Add("itemID", typeof(string));
dt2.Columns.Add("itemName", typeof(string));
//aad 3 DataRows to first DT - ID only
DataRow dt1_1 = dt1.NewRow();
dt1_1["itemID"] = "1";
DataRow dt1_2 = dt1.NewRow();
dt1_2["itemID"] = "2";
DataRow dt1_3 = dt1.NewRow();
dt1_3["itemID"] = "3";
dt1.Rows.Add(dt1_1);
dt1.Rows.Add(dt1_2);
dt1.Rows.Add(dt1_3);
//aad 3 DataRows to first DT - ID & Name
DataRow dt2_1 = dt2.NewRow();
dt2_1["itemID"] = "1";
dt2_1["itemName"] = "ItemOne";
DataRow dt2_2 = dt2.NewRow();
dt2_2["itemID"] = "2";
dt2_2["itemName"] = "ItemTwo";
DataRow dt2_3 = dt2.NewRow();
dt2_3["itemID"] = "3";
dt2_3["itemName"] = "ItemThree";
dt2.Rows.Add(dt2_1);
dt2.Rows.Add(dt2_2);
dt2.Rows.Add(dt2_3);
////////////////////////////////////////////////////////
//replacing code - quite comact - assumed itemId is PK//
////////////////////////////////////////////////////////
foreach (DataRow dr in dt1.Rows)
{
string strSelect = "[itemID] = '"+ dr["itemID"] +"'";
DataRow[] myRow = dt2.Select(strSelect);
if (myRow.Length == 1)
{
dr["itemID"] = myRow[0]["itemName"];
}
}
/////////////////////////////////////////////////////////////////
//dt1 now has itemOne, itemTwo and itemThree instead of 1, 2, 3//
/////////////////////////////////////////////////////////////////
With MySQL I would try:
UPDATE table1 t1, table2 t2
SET t1.itemid = t2.itemname
WHERE t1.itemid = t2.itemid
With MS-SQL I would try
UPDATE t1
SET t1.itemid = t2.itemname
FROM table1 t1 INNER JOIN table2 t2
ON t1.itemid = t2.itemid
I want to convert dataview rowfilter value to datatable. I have a dataset with value. Now i was filter the value using dataview. Now i want to convert dataview filter values to datatable.please help me to copy it........
My partial code is here:
DataSet5TableAdapters.sp_getallempleaveTableAdapter TA = new DataSet5TableAdapters.sp_getallempleaveTableAdapter();
DataSet5.sp_getallempleaveDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
DataView datavw = new DataView();
datavw = DS.DefaultView;
datavw.RowFilter = "fldempid='" + txtempid.Text + "' and fldempname='" + txtempname.Text + "'";
if (datavw.Count > 0)
{
DT = datavw.Table; // i want to copy dataview row filter value to datatable
}
}
please help me...
You can use
if (datavw.Count > 0)
{
DT = datavw.ToTable(); // This will copy dataview's RowFilterd values to datatable
}
You can use DateView.ToTable() for converting the filtered dataview in to a datatable.
DataTable DTb = new DataTable();
DTb = SortView.ToTable();
The answer does not work for my situation because I have columns with expressions. DataView.ToTable() will only copy the values, not the expressions.
First I tried this:
//clone the source table
DataTable filtered = dt.Clone();
//fill the clone with the filtered rows
foreach (DataRowView drv in dt.DefaultView)
{
filtered.Rows.Add(drv.Row.ItemArray);
}
dt = filtered;
but that solution was very slow, even for just 1000 rows.
The solution that worked for me is:
//create a DataTable from the filtered DataView
DataTable filtered = dt.DefaultView.ToTable();
//loop through the columns of the source table and copy the expression to the new table
foreach (DataColumn dc in dt.Columns)
{
if (dc.Expression != "")
{
filtered.Columns[dc.ColumnName].Expression = dc.Expression;
}
}
dt = filtered;
The below code is for Row filter from Dataview and the result converted in DataTable
itemCondView.RowFilter = "DeliveryNumber = '1001'";
dataSet = new DataSet();
dataSet.Tables.Add(itemCondView.ToTable());
my datatable;
dtData
ID | ID2
--------
1 | 2
1 | 3
dtData.Select("ID = 1"); one more rows;
i want row "ID = 1 And ID2 = 3" how to make ?
Do you mean like this?:
dtData.Select("ID=1 AND ID2=3");
Okay, here is how I do such things...
GridFieldDAO dao = new GridFieldDAO();
//Load My DataTable
DataTable dt = dao.getDT();
//Get My rows based off selection criteria
DataRow[] drs = dt.Select("(detailID = 1) AND (detailTypeID = 2)");
//make a new "results" datatable via clone to keep structure
DataTable dt2 = dt.Clone();
//Import the Rows
foreach (DataRow d in drs)
{
dt2.ImportRow(d);
}
//Bind to my new DataTable and it will only show rows based off selection
//criteria
myGrid.DataSource = dt2;
myGrid.DataBind();
Notice in my Select() I put the criteria in Parens between AND and OR
Hope this helps!
Mike V
Better use this :
GridFieldDAO dao = new GridFieldDAO();
//Load My DataTable
DataTable dt = dao.getDT();
//Get My rows based off selection criteria and copy them directly to datatable
DataTable dt2 = dt.Select("(detailID = 1) AND (detailTypeID = 2)").CopyToDataTable();
DataTable dt2 = dt.Select("ID = 1").CopyToDataTable;
make sure dt has rows in it
Here you can copy your contents to another DataTable by using CopyToDataTable method of Linq while selecting the specific rows by filtering.
DataTable dt2 = dt.Select("state = 'FL' ").CopyToDataTable;
Great example and very helpful. Wanted to add one thing - if you need to select on a string use something like:
DataTable dt2 = dt.Select("state = 'FL' ");