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.
Related
I have implemented sorting and pagination in a GridView control. The code is as below :
<asp:GridView ShowHeaderWhenEmpty="True" CssClass="Grid"
AlternatingRowStyle-CssClass="alt" AllowPaging="True" PageSize="15" OnPageIndexChanging="grdAllRequests_PageIndexChanging"
PagerStyle-CssClass="pgr" OnSorting="grdAllRequests_Sorting" AllowSorting="True"
EmptyDataText="No data to show" ID="grdAllRequests" runat="server" AutoGenerateColumns="false"
OnRowDataBound="grdAllRequests_RowDataBound">
Below is the code behind for pagination and sorting
protected void grdAllRequests_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdAllRequests.PageIndex = e.NewPageIndex;
DataTable dt = (DataTable)ViewState["dtAllRequests"];
BindDataBAL bind = new BindDataBAL();
bind.BindGridData(grdAllRequests, dt);
}
protected void grdAllRequests_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtrslt = (DataTable)ViewState["dtAllRequests"];
if (dtrslt.Rows.Count > 0)
{
if (Convert.ToString(ViewState["sortdr"]) == "Asc")
{
dtrslt.DefaultView.Sort = e.SortExpression + " Desc";
ViewState["sortdr"] = "Desc";
}
else
{
dtrslt.DefaultView.Sort = e.SortExpression + " Asc";
ViewState["sortdr"] = "Asc";
}
ViewState["dtAllRequests"] = dtrslt;
grdAllRequests.DataSource = dtrslt;
grdAllRequests.DataBind();
}
}
Now the issue is when i click on any header the sorting is performed correctly but when i try to navigate to next page then the sorting is lost. Not sure what is going wrong. Kindly help.
You have to use DefaultView.ToTable();
dtrslt.DefaultView.Sort = e.SortExpression + " Desc";
dtrslt = dtrslt.DefaultView.ToTable();
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();
}
enter image here
I want to add list data in the html Table.
The list data can be various, so table rows were dynamic and if List size increase user can use paging in table to move next...
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
Date1.Add(sdr["Date"].ToString());
Time.Add(sdr["Time"].ToString());
Event.Add(sdr["Event"].ToString());
Venue.Add(sdr["Venue"].ToString());
}
}
conn.Close();
}
}
for (int i = 0; i < Date1.Count; i++) {
string Date11 = Date1[i];
string Time1 = Time[i];
string Event1 = Event[i];
string Venue1 = Venue[i];
if(Venue1.Contains(country) || Venue1.Contains(Code[0]))
{
Result.Add( Date11 + " " + Time1 + " " + Event1 + " " + Venue1);
}
}
Can someone kindly give me code/hint which can i use in my Project. I will be very thankful to you.
The example below takes care of the following requirements which you've listed in the question:
Generates an HTML table containing your data
Has paging functionality
Supports dynamic columns
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
}
private DataTable GetEvents()
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
using(var command = new SqlCommand("SELECT TOP 100 Date,Time,Event,Venue FROM Event",connection))
{
connection.Open();
var adapter = new SqlDataAdapter(command);
adapter.Fill(table);
connection.Close();
}
}
int rows = table.Rows.Count;//Place breakpoint to make sure table has rows
return table;
}
protected void gvEvents_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEvents.PageIndex = e.NewPageIndex;
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
.ASPX:
<form id="form1" runat="server">
<asp:GridView ID="gvEvents" runat="server" AllowPaging="true" PageSize="2" OnPageIndexChanging="gvEvents_PageIndexChanging">
</asp:GridView>
</form>
Output:
I have a gridView:-
<asp:GridView ID="gvw_Lab_Details" AllowPaging="true" PageSize="3" OnPageIndexChanging="gvw_Lab_Details_PageIndexChanging" runat="server" EmptyDataText="No Previous Enrollments were Found." SkinID="gridviewSkin2">
</asp:GridView>
On the server side:-
public DataSet LabDS
{
get { return (DataSet)ViewState["LabDetails"]; }
set { ViewState["LabDetails"] = value; }
}
#region Initialize.
string _Requestdate = string.Empty;
string _ID = string.Empty;
#endregion
#region Page Methods
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// extracting the Lab_Requested Date from Query String.
_Requestdate = (Request.QueryString["info"]);
_ID = ((MyStateBag)Session["MyStateBag"]).MemberID;
GetLabResults();
}
}
#endregion
private void GetLabResults()
{
using (SqlConnection cn = new SqlConnection(DBConnect.SqlServerConnection))
{
cn.Open();
#region Pulls Existing Enrollments from SQL
DataTable dt = new DataTable();
using (SqlCommand cm = cn.CreateCommand())
{
// Create SQL Statement
StringBuilder ct = new StringBuilder();
ct.AppendLine("SELECT DISTINCT Key, Date, "
+ "NAME_First + ' ' + NAME_MI + ' ' + NAME_Last, "
RESULT_VALUE, RESULT_UNITS ");
ct.AppendLine("FROM [test].[dbo].[test]");
ct.AppendLine("WHERE Date = #Date and ID = #ID");
cm.Parameters.AddWithValue("#Date", _Requestdate);
cm.Parameters.AddWithValue("#ID", _ID);
cm.CommandType = CommandType.Text;
cm.CommandText = ct.ToString();
// Execute
cm.ExecuteNonQuery();
#region Populate Gridview with extracted Data.
SqlDataAdapter dr = new SqlDataAdapter(cm);
dr.Fill(dt);
this.LabDS = new DataSet();
this.LabDS.Tables.Add(dt);
LoadGridView(1);
#endregion
}
#endregion
private void LoadGridView(int PageIndex)
{
gvw_Lab_Details.DataSource = this.LabDS;
gvw_Lab_Details.DataBind();
}
protected void gvw_Lab_Details_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
LoadGridView(e.NewPageIndex);
}
However my indexing doesn't seem to be working aka results of 3 or less are shown on the first page but once there are more than 4 results I get my default "No previous enrollments were found". Any insights on where I am going wrong?
this a .NET web application.
You're missing one important piece of information. You have to tell the GridView which page you are changing to:
protected void gvw_Lab_Details_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvw_Lab_Details.PageIndex = e.NewPageIndex;
LoadGridView(e.NewPageIndex);
}
//Sort User Table
private void SortGridView(string sortExpression, string direction)
{
DataTable dataTable = BindGridView(Session["useremail"].ToString()).Tables[0];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = sortExpression + direction;
UserTable.DataSource = dataView;
UserTable.DataBind();
}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, " ASC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, " DESC");
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
When I Edit a user and update the edit or do some search, and clear the search the page loads and the sort is lost,
private DataSet BindGridView(string email)
{
.......
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
.....
BindGridView(Session["useremail"].ToString());
}
everytime the page loads or some postback is done the sort is lost how to retain the sort.
Page load
if (PermissionList.Any(item => item.Equals("Edit user")))
{
if (!IsPostBack)
{
BindGridView(Session["useremail"].ToString());
}
}
Whenever you perform a new sort on your gridview, store the sort expression in a hidden label, or field, and anytime you re-load/bind your gridview, use your saved sort expression to re-sort the table.
.aspx
<asp:Label id="lblHidSortExp" runat="server" visible="false"></asp:Label>
.aspx.cs
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = lblHidSortExp.Text;
if(sortExpression == e.SortExpression)
sortExpression += " DESC";
else
sortExpression == e.SortExpression;
//not sure if this is exactly how you get your datatable, but you get the idea
DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
myView.Sort = sortExpression;
marksGridView.DataSource = myView;
marksGridView.DataBind();
//save sort state
lblHidSortExp.Text = sortExpression;
}
So say in your update function, use your saved sort exp
protected void btnUpdate_Click(object sender, EventArgs e)
{
.....//do update in db
//reload your table in dataview
DataView myView = new DataView(/*load table*/);
//do sort
myView.Sort = lblHidSortExp.Text;
//bind gridview
marksGridView.DataSource = myView;
marksGridView.DataBind();
}
I had a similar problem, the way I aproached this was to save the sort values in the session, then just reset them in Page_load after they are lost.