C# - How do I sort a DataTable by date - c#

I have a datatable that has a date column, but I am stumped as to how to sort it by that column. Any suggestions?

DataView view = DataTable.DefaultView;
view.Sort = "DateColumn";

Related

find and display datarows in datagridview

I faced to issue of displaying datarows from DataTable from DataSet. I used a temporary table. I found rows that I need by id and copy it to temporary table and then diplay in DataGridView. Is there any way to find and display rows that I need in DataGridView directly from DataTable from DataSet without using any temporary DataTable's? I've tried to do this by hiding and unhiding rows in DataGridView, but sadly it didn't worked out
private DataTable tblFiltered =
ds.Tables("GRAPHICS").AsEnumerable().Where(row =>
row.Field<int>("GRAPHIC_ID") == graphId && row.Field<int>
("GRAPHIC_ID")).CopyToDataTable;
Assuming that DataSet 'ds' containing Table 'GRAPHICS',We can use DataView to Display filtered records in DataGridView. Ex.
int graphId = 2; //Assuming
DataView dv = ds.Tables["GRAPHICS"].AsDataView();
dv.RowFilter = "GRAPHIC_ID = " + graphId; //RowFilter :: Expression used to filter which rows are viewed !!
dataGridView.DataSource = dv.ToTable();
You can use filter
(DatagridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("GRAPHIC_ID= '{0}'", graphId);

DataTable Sorting without creating new DataTable with maintaining RowState

I am using DataTable. In which I want to sort on particular columns without creating copy. I have also tried with DataTable.Select() but it required new table for sorted output which will be not worked for me as my source datatable is bound with control.
You can take any example of DataTable
So how can I achieve the task?
Below code will help you to achieve your requirement
IEnumerable<DataRow> data = from dt in dtTemp.AsEnumerable()
orderby dt.Field<Int32>("IDColumn"), dt.Field<String>("NameColumn") ascending
select dt;
Below code as an example:
DataTable dt = new DataTable();
//Populate dt here
dt.DefaultView.Sort = string.Format("{0} {1}", "column name here", "ASC"); //sort ascending
dt = dt.DefaultView.ToTable();

gridView.DataSource as DataTable is setting a null in asp.net

I am setting my gridview.datasource into a datatable variable as below:
DataTable dt = gvPaymentHistory.DataSource as DataTable;
The gvPaymentHistory.DataSource has a record, however, the dt is null after that line has executed. How can I pass the Datasource records to dt?
EDIT
DataSource is List collection of a class object. It's not a DataSet
Simple way is to store the data source of the grid in view source when u r binding the data to the grid and then retrieve it from the view source every time you need it.
Gridview.Datasource = yourdatasource;
ViewState["mydatasource"] = yourdatasource;
While retrieving
DataTable dt = ViewState["mydatasource"] as DataTable;
Hope this solves your problem.
Try This Way: Use BindingSource
BindingSource bs = (BindingSource)gvPaymentHistory.DataSource;
DataTable dt =((YourDataSetType) (bs.DataSource)).Tables[0];
EDIT
if the bidning type is list than try out
List<CodeEntity> data= gvPaymentHistory.DataSource as List<CodeEntity>;
or
List<CodeEntity> codes = (List<CodeEntity>)gvPaymentHistory.DataSource;
check this
if(gvPaymentHistory.DataSource is DataTable)
DataTable dt = gvPaymentHistory.DataSource as DataTable;
if(gvPaymentHistory.DataSource is DataView )
DataView dv = gvPaymentHistory.DataSource as DataView;

Dataset Sorting using C# on a column with Datetime datatype

I am having a dataset (Dataset ds) and below you can find the field with demo data inside the dataset.
In my Dataset , their is column with name Date (Datatype- DateTime) and i want to sort this column.I cant do the sorting from SQl because the Dataset is a merge of 2 Different Dataset.
Please help me that how i do the sorting in dataset.
Date Volume
07/19/201211:30AM 12
07/18/201201:30PM 13
07/17/201203:30PM 22
This is a simple Linq-To-DataSet approach:
IEnumerable<DataRow> orderedRows = dataSet.Tables[0].AsEnumerable()
.OrderBy(r => r.Field<DateTime>("Date"));
Now you can use that as DataSource or enumerate it in a foreach. If you need to materialize it, you might want to create a new DataTable from it:
DataTable tblOrdered = orderedRows.CopyToDataTable();
You can create a data view from your data-set.
Then you can use the DataView.Sort Property to sort your data.
eg.
DataView myDataView = DT.DefaultView;
myDataView.Sort = "Date DESC";
Read more about Introduction to Filtering and Sorting in Datasets
Using Dataview you can sort your Datatable.
Just put your Datatable in Dataview
Look at the following example :
You have dtlog table which having two columns one is date and another one is detials.
you want to sort your datatable by date column.
DataTable dtlog = new DataTable();
dtlog.Columns.Add("date");
dtlog.Columns.Add("details");
1.create dataview and put your datatable in view
DataView dtview = new DataView(dtlog);
string sortstring = "date DESC"; // sorting in descending manner
dtview.Sort = sortstring;
2.Create another table where you can save your sorted dataview
DataTable dtsort =dtview.ToTable();
You can do this by a DataView. If your column which is holding datetime is a datetime column
DataView dv = DataTable.DefaultView;
dv.Sort = "DateTime-ColumnName ASC";
It will not work on string column holding datetime as string.
The DataView of a DataTable have a sort property please pass the column name to it
E.g.
dataSet1.Table[0].DefautlView.Sort = "ColumnName";
default sort is by ascending order
For more see link http://msdn.microsoft.com/en-us/library/system.data.dataview.sort(v=vs.100).aspx
I find my solucion is add more columns to Datatable where we can save each part of a DateTime:
Tabla.Columns.Add("year", typeof(DateTime));
Tabla.Columns.Add("month", typeof(DateTime));
Tabla.Columns.Add("day", typeof(DateTime));
then we can sort our datatable with a DataView:
DataView myDataView = DT.DefaultView;
case 1: ASC
myDataView.Sort = "year asc, month asc, day asc";
case 2: DESC
myDataView.Sort = "year desc, month desc, day desc";
Tabla = myDataViwe.toTable();
result is our datatable sorted for a dateTime
It worked for Me:
dataTableEmpSurvey.DefaultView.Sort = "SNO";
var dataTableSorted = dataTableEmpSurvey.DefaultView.ToTable();
https://www.codeproject.com/Questions/219205/How-To-Sort-Datatable-in-csharp-net

How to sort data in GridView in asp.net

How to sort datatable obtained by GridView according to some column.
I am trying to do something like this but it is not working.
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
if (sender.GetType() != typeof(GridView))
return;
DataTable dt = (DataTable)((GridView)sender).DataSource;
DataTable dtClone = dt.Clone();
dt.AsEnumerable().OrderBy(row => row.Field <string>(e.SortExpression));
((GridView)sender).Source(dtClone);
}
You can either re-bind the gridview to the sorted datatable, or you can apply the sort expression to the gridview itself rather than the underlying bound table.
This is a pretty good summary with links to examples:
http://msdn.microsoft.com/en-us/library/hwf94875.aspx
Add the attributes OnSorting="gridView_Sorting" AllowSorting="true" in Gridview
and SortExpression="ColumnName" in the column
and implement OnSorting Event.
check the links
Sorting the GridView's Data
How to sort the data in grid view?
How to sort data into GridView
Sorting Data in a GridView
How to sort GridView?
I've done something like this in the past to sort a DataTable:
DataTable dt = new DataTable(); // your data table
dt.DefaultView.Sort = "your_field" + "sort_direction";
DataView dv = new DataView(dt);
dv.Sort = ("your_field" + "sort_direction");
yourGridView.DataSource = dv;
When sorting, make sure to cast your table to a DataView. You'll save yourself a lot of time over manually implementing sorting methods.

Categories