Is it possible to sort an ASP.NET GridView using DataTable.Select("", sortExpression)?
I have a regular GridView with AllowSorting="true" and OnSorting="grdEmployees_Sorting".
protected void grdEmployees_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = getDataTable();
var sortExprOrder = e.SortDirection == SortDirection.Ascending ? " ASC" : " DESC";
var rows = dt.Select("", string.Format(e.SortExpression + "{0}", sortExprOrder));
grdEmployees.DataSource = rows;
grdEmployees.DataBind();
}
Not sure why, but this does not work. The grid shows a bunch of rows with three columns, RowError, RowState, and HasErrors (contains rows with all empty checkboxes).
Am I doing something wrong?
You don't need select for sorting DataTable.Select is for filtering
This how you sort
protected void grdEmployees_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = getDataTable();
var sortExprOrder = e.SortDirection == SortDirection.Ascending ? " ASC" : " DESC";
DataView dv = new DataView(dt);
dv.Sort = string.Format("{0} {1}",
e.SortExpression, sortExprOrder);
grdEmployees.DataSource = dv;
grdEmployees.DataBind();
}
Related
I have data in a DataTable object and I want to retrieve specific data from a data table on some certain conditions, for to query a data table using its select method
My database is MySQL 8.0.17 version
I tried this code without success because the error on VS 2019 is
The [ABW] column could not be found string
But the [ABW] don't is the name of column but value of column CountryCode
What's wrong with this code?
Please, any help?
DataTable cgv = new DataTable();
DataTable dtCustomers;
DataTable dtOrders;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Create a datatable as a DataSource of GridViews
dtCustomers = new DataTable(); // parent gridview datasource
dtOrders = new DataTable(); // child gridview datasource
dtOrders = GetData("SELECT CountryCode, Language, IsOfficial, Percentage FROM `tCustomers`");
cgv = dtOrders; // set child datatable to temporary datatable
dtCustomers = GetData("SELECT CountryCode, Language, IsOfficial, Percentage FROM `tCustomers`;");
gvCustomers.DataSource = dtCustomers;
gvCustomers.DataBind();
}
}
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CountryCode = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = ((GridView)e.Row.FindControl("gvOrders"));
dtOrders.Columns[0].ColumnName = "CountryCode";
DataRow[] dr = dtOrders.Select(dtOrders.Columns[0].ColumnName + "=" + CountryCode.ToString());
gvOrders.DataSource = dr; // set child datatable to parent gridview as datasource
gvOrders.DataBind();
}
}
Like this:
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CountryCode = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = ((GridView)e.Row.FindControl("gvOrders"));
cgv.DefaultView.RowFilter = "CountryCode='" + CountryCode.ToString() + "'";
gvOrders.DataSource = cgv;
gvOrders.DataBind();
}
}
I don't Understand what is going on :( I'm struggling with this code 4 days ago...
I have 2 methods that returns TWO datatables, I Merge them in one table, and bind a BindingSource to the DT then bind the Datagridview to the Bindingsource
private void chld_LogByName_Load(object sender, EventArgs e)
{
dgvLogByName.DataSource = bs1;
PreviewKN(); PreviewRD();
dt1.Merge(dt2);
bs1.DataSource = dt1;
}
So I can Search in the DGV like that:
private void txtLName_TextChanged(object sender, EventArgs e)
{
BindingSource bs = new BindingSource();
bs.DataSource = dgvLogByName.DataSource;
string columnName = dgvLogByName.Columns[5].Name.ToString();
bs.Filter = columnName + " like '%" + txtFName.Text + "%'";
dgvLogByName.DataSource = bs;
}
THIS WORKS PERFECT...
But when I turn to that one, it works until it load the LocalDataTable, but it doesn't bind the able to the DGV, so the DT has rows, but the DGV has 0.
private void txtFName_TextChanged(object sender, EventArgs e)
{
try
{
if (dt1 != null && dt1.Rows.Count > 0)
{
DataRow[] dr = dt1.Select("F_Name LIKE '%"+ txtFName.Text +"%'");
DataTable localTable = new DataTable();
if (dr.Length > 0)
{
dgvLogByName.DataSource = null;
foreach (DataRow row in dr)
{
localTable.ImportRow(row);
}
dgvLogByName.DataSource = localTable;
dgvLogByName.Refresh();
}
Please Help..
I have a grid view where I am implementing both paging and sorting. When I sort the table and select page 2, then the sorting is lost and the second 20 records are displayed in desc as mentioned in gridview binding
private DataSet BindGridView(string field)
{
DataSet ds = new DataSet()
string userQuery = "Select tbl_User.UserID, tbl_User.FirstName from tbl_user order by tbl_user.UserID desc";
UserTable.DataBind();
return ds;
}
<asp:GridView ID="UserTable" runat="server" PageSize="20" AllowPaging="True"
SelectedIndex="0" DataKeyNames="UserID" OnRowDataBound="UserTable_RowDataBound"
AutoGenerateColumns="false" OnPageIndexChanging="gridView_PageIndexChanging" AllowSorting="true" OnSorting="gridView_Sorting">
How can I retain the sorting and perform the paging, I store the sort state in the session, how can i use that to perform paging.
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
UserTable.PageIndex = e.NewPageIndex;
UserTable.DataBind();
DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = null;
if ((Session["UsersortExpression"] == null))
{
sortExpression = null;
}
else
{
sortExpression = (Session["UsersortExpression"].ToString());
}
if (sortExpression == e.SortExpression)
{
sortExpression += " DESC";
}
else
{
sortExpression = e.SortExpression;
}
DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
myView.Sort = sortExpression;
UserTable.DataSource = myView;
UserTable.DataBind();
//save sort state
Session.Add("UsersortExpression", sortExpression);
}
You could apply sorting on your source query using ViewState String vars to store sort field and sort direction:
Ensure ViewState vars are set with defaults:
ViewState["sortDir"] = "DESC";
ViewState["sortField"] = "tbl_user.UserID";
Then, modify your query string:
string userQuery =
"Select tbl_User.UserID, tbl_User.FirstName " +
"from tbl_user " +
"ORDER BY " + (String)ViewState["sortField"] + " " + (String)ViewState["sortDir"];
Include in OnSorting:
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Set new sort direction and sort field
if ((String)ViewState["sortDir"] == "DESC"){ViewState["sortDir"] = "ASC";}
else { ViewState["sortDir"] = "DESC"; }
ViewState["sortField"] = e.SortExpression;
// Rebind
...
}
This way, your source data is pre-sorted and you don't need to worry about using myView.Sort or running into any paging/sorting conflicts.
Please refer to this article about paging and sorting in asp.net gridview.
Hope that helps.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using BiscomFax;
namespace FaxServer
{
public partial class _Default : System.Web.UI.Page
{
public const string vsColumn = "Column";
public const string vsSortDirection = "SortDirection";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
ViewState[vsColumn] = "";
List_Click(ActivityButton, e);
}
protected void List_Click(object sender, EventArgs e)
{
//using (new Impersonator("administrator", "mlabs.com", "100%secure*"))
//{
try
{
Fax fax = new Fax();
ConnObj cnObj = GetConfiguration();
Button btn = (Button)sender;
string sort = "";
DataTable dt = new DataTable();
switch (btn.CommandName)
{
case "Activity":
sort = "DateTime";
dt = fax.GetActivityLog(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
case "Message":
sort = "DateTime";
dt = fax.GetMessageStatus(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
case "Pending":
sort = "DeliveryTime";
dt = fax.GetPendingList(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
default:
sort = "DateTime";
dt = fax.GetActivityLog(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
}
GridView1.DataSource = dt;
GridView1.Sort(sort, SortDirection.Descending);
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
//}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
DataView dv = new DataView(dt);
string oldSort = ViewState[vsColumn].ToString();
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(e.SortDirection);
if (dv.Sort == oldSort)
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(SortDirection.Descending);
ViewState[vsColumn] = dv.Sort;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
i am having a very difficult time sorting the contents of this gridview, i know that i am binding correctly becuase the data is showing but the data does not get sorted at all by DateTime. what am i doing wrongly?
Lets look at this line
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(e.SortDirection);
While testing, when you put a breakpoint on this line what value did e.SortExpression have?
Your databind is correct.
here is a nice article for sorting in gridview:
http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=1418
[update]
Your code has several inconsistency. You probably need to implement it again.
allowsorting must be true
each grid column must declare the sortexpression
you can't read the data back from the gridview's datasource
you need to read the data from your database on each postback, i.e. sorting
here is a good example in C#:
http://programming.top54u.com/post/ASP-Net-2-0-Gridview-Sorting-Using-C-sharp.aspx
You could sort the datatable by setting it's property datatable.defaultview.sort. Don't know of the top of my head whether you need to bind the datatable or the datatable.defaultview after that though.
Try This code
protected void grdList1_Sorting(object sender, GridViewSortEventArgs e)
{
fillgrid();
string sortstr = e.SortExpression;
DataView dview = new DataView(dtable);
if (sortstr == "asc")
dview.Sort = e.SortExpression + " desc";
else
dview.Sort = e.SortExpression + " asc";
grdList1.DataSource = dview;
grdList1.DataBind();
}
just check allowsorting property on aspx page in gridview control
It may be false.
please make it true and then check sorting.
I want to convert my GridView to a DataTable. Note: The GridView doesn't have a DataSource!
I want to sort the DataTable and put it back to the GridView, is it possible? Important is that my GridView must be sorted.
Thank you in advance.
Put your DataTable in a ViewState when you bind for the first time.
gridView1.DataBind();
ViewState["dtbl"] = YourDataTable
and then do like...
protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = ViewState["dtbl"] as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
ComponentGridView.DataSource = dataView;
ComponentGridView.DataBind();
}
}
private string ConvertSortDirection(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
Also take a look at this MSDN article http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx