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.
Related
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);
I want to sort my datagrid view column which is non data bound. so please help me . following is the code
private void dgvDailyEntry_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
this.dgvDailyEntry.Rows[e.RowIndex].Cells["sno"].Value = (e.RowIndex + 1).ToString();
}
sort
Thanks in Advance
If it's not bound, I'd assume you have a datatable assigned as datasource. If you can sort the data while obtaining the datatable, the best is to sort it right there. If you can't (i.e. data are generated in random order), sort the datatable then.
C#
Datatable dt; // that is the source datatable
DataView SortedDataView = new DataView();
SortedDataView = dt.DefaultView;
SortedDataView.Sort = "COlumnNameToSortBy DESC";
dt = SortedDataView.ToTable();
VB.NET:
Dim dt as Datatable ' that is the source datatable
Dim SortedDataView As New DataView
SortedDataView = dt.DefaultView
SortedDataView.Sort = "COlumnNameToSortBy DESC"
dt = SortedDataView.ToTable()
If you somehow don't have datatable, I'd certainly recommend to implement it. It's a good practice even if you don't need sorting and such.
I have been working on asp.net/C# project. I could bind the DataTable to gridview. But i have a situation where i don't want to bind all the records in DataTable. is there any method to bind only few records to gridview? any Alternatives to GridView.DataBind()?
Thank you
try this,
using datatable select query you can achieve this,
for example,
DataTable dt=yourdata;
DataRow[] dr=dt.Select("columnname='Maths'");
foreach (DataRow row in dr) {
dt.ImportRow(row);
}
GridView1.DataSource=dt;
GridView1.DataBind();
where Maths = your search criteria.
You can add the rows manually, i.e. without using a data source.
var newRowIndex = dataGridView1.Rows.Add(firstValue, secondValue, thirdValue);
You might use it like this:
foreach (System.Data.DataRow row in myDataTable.Rows)
{
if(meets my criteria...)
{
dataGridView1.Rows.Add(row["Column1"], row["Column2"], row["Column3"]);
}
}
In fact, this may be a better solution as it allows you to sort columns easily in the UI whereas binding to a data source does not allow that.
Use DataView for the DataTable, So that you can able to filter records and assign the dataview to Grid.
for example:
DataView dv = new DataView(DataTable, "Column1=Value", "Column2", DataViewRowState.CurrentRows);
I have a FormView with paging bound to a SqlDataSource. I am trying to find out how to access the datasource currently bound to the FormView. For example, if I am on page 2, how do I access the second row of the datasoure? I only need to read certain values for comparison; the data will not be changed. Is it possible to get this as a DataRow or DataTable object?
Use this code to access the DataTable in your SQLDataSource
DataSourceSelectArguments args = new DataSourceSelectArguments();
SqlDataSource mds = (SqlDataSource)MyFormView.DataSourceObject;
DataView view = (DataView)mds.Select(args);
DataTable dt = view.ToTable();
DataRow dr2 = dt.Rows[1];
I tested this with a ListView, not a FormView, hope it works for you as well
I am using a gridview with sqldatasource. How to get back the datasource in the codebehind as a datatable?
Use System.Data.DataTable dt = (System.Data.DataTable)gview.DataSource; if you are binding a DataTable.
You can even extract the DataTable out of DataSet if you are binding DataSet as
System.Data.DataTable dt2 = (System.Data.DataTable)((System.Data.DataSet)gvValidDA.DataSource).Tables[0]; you will have to check the index of your table or table name as you prefer.
Happy coding.
Edited
Use SqlDataSource.Select Method and assign it to a dataview
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
Then extract the datatable using
DataTable dt = (DataTable)dv.ToTable();
The actual data is not stored in the Gridview properties as the above answers pertain.
Using direct casting to the Gridview.DataSource is not enough, as it's actually NULL when the gridview has rendered!
You have to either reload the data directly from the SQL datasource...
DataSourceSelectArguments dss = new DataSourceSelectArguments();
DataView dvS = sdsADDorREMstudentData.Select(dss) as DataView;
DataTable dtS = dvS.ToTable() as DataTable;
if (dtS != null)
{
... etc...
}
Or you can use the ViewState to retain the data before the Gridview has rendered.
DataView dvClasses = (DataView)sdsClasses.Select(DataSourceSelectArguments.Empty);
gvStudents.DataSourceID = "sdsClasses";
gvStudents.DataSource = null; // Null out the source, as we have a SourceID instead
gvStudents.DataBind();
//save the data in a viewstate for later use (to control adding and removing students, without doing a postback! See ADD & REM methods below)
DataView dv = (DataView)dvClasses;
DataTable dt = new DataTable();
if (dv != null)
{
dt = dv.ToTable();
ViewState["gv"] = dt;
}
And use the ViewState to turn it back into a DataTable, when you need to use the data AFTER the Gridview has rendered...
DataTable dt = (DataTable)ViewState["gv"];