C# Sorting lost when going to new page - c#

I have an issue with my sorting when navigating between pages. When I go to a new page, the sorting order is lost and the user has to sort again.
I have ran through my code and know the issue lies in PageIndexChanging event of the gridview. Where am rebind the gridview with fresh data.
However, I am not sure how to avoid this? How do I store the sort order when rebinding the gridview? ViewState perhaps?
Any suggestions please?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateProductClass();
PopulateProduct();
PopulateOrderList();
}
}
private void PopulateOrderList()
{
DateTime d;
DateTime d2;
CustomerInfo ki = CustomerInfoProvider.GetCustomerInfoByUserID(CooneenHelper.GetUserImpersonisationID());
int nKustomerID = ki.CustomerID;
DataTable dts = new DataTable();
dts.Columns.Add("OrderDate", typeof(DateTime));
dts.Columns.Add("OrderNumber", typeof(string));
dts.Columns.Add("OrderItemSKUName", typeof(string));
dts.Columns.Add("SKUNumber", typeof(string));
dts.Columns.Add("OrderItemStatus", typeof(string));
dts.Columns.Add("OrderItemUnitCount", typeof(string));
dts.Columns.Add("mtrx_Code2", typeof(string));
QueryDataParameters qdp = new QueryDataParameters();
qdp.Add("#CustomerID", nKustomerID);
if (drpProductClass.SelectedValue.ToString() != "0" || drpProductClass.SelectedValue.ToString() == null) { qdp.Add("#OrderItemWRClass", drpProductClass.SelectedItem.ToString()); }
if (drpProduct.SelectedValue.ToString() != "0") { qdp.Add("#OrderItemSKUID", drpProduct.SelectedValue.ToString()); }
if (txtStartDate.Text != "") { d = DateTime.Parse(txtStartDate.Text); qdp.Add("#OrderItemDateFrom", d.ToString("yyyy-MM-dd")); }
if (txtEndDate.Text != "") { d2 = DateTime.Parse(txtEndDate.Text); qdp.Add("#OrderItemDateTo", d2.ToString("yyyy-MM-dd")); }
DataSet ds = gc.ExecuteQuery("CN_GetOrderItemByCustID", qdp, QueryTypeEnum.StoredProcedure, true);
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow drNew = dts.NewRow();
drNew["OrderDate"] = ValidationHelper.GetDateTime(dr["OrderDate"], DateTime.Now).ToShortDateString();
drNew["OrderNumber"] = dr["OrderNumber"].ToString();
drNew["OrderItemSKUName"] = dr["OrderItemSKUName"].ToString();
drNew["SKUNumber"] = dr["SKUNumber"].ToString();
drNew["OrderItemStatus"] = dr["OrderItemStatus"].ToString();
drNew["OrderItemUnitCount"] = dr["OrderItemUnitCount"].ToString();
drNew["mtrx_Code2"] = dr["mtrx_Code2"].ToString();
dts.Rows.Add(drNew);
}
//Clear the TextBox
litResults.Text = String.Empty;
if (dts.Rows.Count == 1)
litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";
else
litResults.Text = "" + dts.Rows.Count.ToString() + " Order Items";
try
{
Session["Data"] = dts;
}
catch(Exception ex)
{
throw ex;
}
gvOrderItems.Visible = true;
gvOrderItems.DataSource = dts.DefaultView;
gvOrderItems.DataBind();
if (dts.Rows.Count > 1) litResults.Text += " - Showing page " + (gvOrderItems.PageIndex + 1).ToString() + " of " + gvOrderItems.PageCount.ToString();
}
private string SortCriteria
{
get
{
if (ViewState["sortCriteria"] == null)
{
ViewState["sortCriteria"] = "";
}
return ViewState["sortCriteria"].ToString();
}
set
{
ViewState["sortCriteria"] = value;
}
}
public SortDirection SortDirection
{
get
{
if (ViewState["SortDirection"] == null)
{
ViewState["SortDirection"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["SortDirection"];
}
set
{
ViewState["SortDirection"] = value;
}
}
protected void gvOrderItems_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
string direction = string.Empty;
DataTable dt = (DataTable)Session["Data"];
if (dt.Rows.Count > 0)
{
DataView dataView = new DataView(dt);
if (SortDirection == SortDirection.Ascending)
{
SortDirection = SortDirection.Descending;
direction = " DESC";
}
else
{
SortDirection = SortDirection.Ascending;
direction = " ASC";
}
dataView.Sort = sortExpression + direction;
gvOrderItems.DataSource = dataView;
gvOrderItems.DataBind();
}
}
protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
gvOrderItems.PageIndex = e.NewPageIndex;
PopulateOrderList();
}

Maybe you're databinding the GridView on every postback from Page_Load.
You should do that only at the first time. Use the Page.IsPostBack property:
protected void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
// GridBind here
}

Resolved my issue thanks to Vignesh on suggesting of using ViewState. However I choose to use a Session variable.
Inside the sorting event handler, after the sorting is carried out I stored the sorted list in a Session Session["SortedView"] = dataView;. Now during the PageIndexChanging1 I check if this session variable is empty and use accordingly.
protected void gvOrderItems_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
gvOrderItems.PageIndex = e.NewPageIndex;
if (Session["SortedView"] != null)
{
gvOrderItems.DataSource = Session["SortedView"];
gvOrderItems.DataBind();
}
else
{
PopulateOrderList();
}
}

Related

Disable gridview on checkboxlist selected value

I have a Checkboxlist in which Items are binded from database.
Now what I want is, whenever user checks Registration / Conveyance Deed value from the list, Then the gridview should get disabled.
I tried with below code.
protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlStatus.SelectedValue == "30" && strMode == "M")
{
GridExpInfo.AllowAddingRecords = false;
}
else
{
GridExpInfo.AllowAddingRecords = true;
}
}
What happens is, it always shows the selected value of Agreement from the list, which is 20
Below is the screenshot of the list
update
ASPX:-
<asp:CheckBoxList ID="ddlStatus" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged">
</asp:CheckBoxList>
C#
private void BindStatus()
{
DataTable dtstatus = new DataTable();
OracleDataAdapter dastatus = new OracleDataAdapter("SELECT lookup_code agr_type_code, meaning agr_type " +
"FROM apps.fnd_lookup_values_vl " +
"WHERE (NVL ('', territory_code) = territory_code OR territory_code IS NULL " +
") AND lookup_type = 'XXACL_FARM_AGR_TYPE' " +
"AND (lookup_type LIKE 'XXACL_FARM_AGR_TYPE') " +
"AND (view_application_id = 0) " +
"AND (security_group_id = 0) " +
"ORDER BY 1", ObjPriCon);
dastatus.Fill(dtstatus);
ddlStatus.DataTextField = "agr_type";
ddlStatus.DataValueField = "agr_type_code";
ddlStatus.DataSource = dtstatus;
ddlStatus.DataBind();
}
You can set property AllowUserToAddRows to false inside code as shown below.
this.yourGrid.AllowUserToAddRows = false;
this.BindDataGridView();
And use ForEach loop for checking your condition. Now you check all selected items not only first selected.
protected void ddlStatus_OnSelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem li in ddlStatus.Items)
{
if (li.Value == "30" && strMode == "M")
{
GridExpInfo.AllowUserToAddRows = false;
}
else
{
GridExpInfo.AllowUserToAddRows = true;
}
}
You can also use LINQ for checking it.
protected void ddlStatus_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (strMode == "M")
{
var disable = (from ListItem item in ddlStatus.Items.OfType<ListItem>()
where item.Selected
where item.Value == "30"
select int.Parse(item.Value)).Any();
if (disable)
{
GridExpInfo.AllowUserToAddRows = false;
}
else
{
GridExpInfo.AllowUserToAddRows = true;
}
}
}
Try this snippet
protected void myCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)
{
bool enableGrid = true;
foreach (ListItem listItem in ddlStatus.Items)
{
if (listItem.Value == "30" && listItem.Selected == true)
{
enableGrid = false;
}
}
if (enableGrid == true)
{
//enable grid and/or row inserts here
Label1.Text = "enabled";
}
else
{
//disable grid and/or row inserts here
Label1.Text = "disabled";
}
}

why the gridview_sorting method is not fired in c# asp.net?

I have a method called gridview1_Sorting which works correctly when I click on header in table, but I want to call it automatically after the text inside search box changes and when the table change to the next from paging footer.
I think I should call this method manually from grdView_PageIndexChanging and from the method which detects checkbox state changes:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SetSortDirection(SortDireaction);
firstTable.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
DataView dv = new DataView(firstTable);
GridView1.DataSource = firstTable;
GridView1.DataBind();
SortDireaction = _sortDirection;
int columnIndex = 0;
foreach(DataControlFieldHeaderCell headerCell in GridView1.HeaderRow.Cells)
{
if (headerCell.ContainingField.SortExpression == e.SortExpression)
{
columnIndex = GridView1.HeaderRow.Cells.GetCellIndex(headerCell);
}
}
GridView1.HeaderRow.Cells[columnIndex].Controls.Add(sortImage);
}
Image sortImage = new Image();
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "Asc")
{
_sortDirection = "Desc";
sortImage.ImageUrl = "~/images/u.png";
} else
{
_sortDirection = "Asc";
sortImage.ImageUrl = "~/images/d.png";
}
}
I tried the following two options:
this.GridView1.Sorting +=
new GridViewSortEventHandler(GridView1_Sorting);
and
this.GridView1.Sorting += GridView1_Sorting;
but none seems to work.
I solve d this problem by using gridview1.sort(e.SortExpression,SortDirection.Ascending);
but I think there is another solution by firing gridview.sorting event but I cant do it

Keep State of Gridview

I have a gridview and I'm trying to keep the state of. Currently I have it where the user can edit inline( from within the gridview). Regularly I got this working:
protected void GridViewTower_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridViewTower.EditIndex = e.NewEditIndex;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
protected void GridViewTower_CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
GridViewTower.EditIndex = -1;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
Problem is, I have 3 other features such sorting, dropdown that filters gridview, and a button search which also filters the girdview. When inline editing within any 3 of those modes, I can't control the state in which the gridview is in. Inside my gridview tag, I have both EnableViewState and ViewStateMode set to true.
How can I keep the state of the gridview within these modes?
public void LoadData()
{
if (Session["GridView"] != null)
{
GridViewTower.DataSource = Session["GridView"];
GridViewTower.DataBind();
//Response.Redirect("TowerManagement.aspx"); //
//Session["GridView"] = null;
}
else
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var tower = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
RangeName = t.Range.RangeName
}).ToList();
GridViewTower.DataSource = tower;
GridViewTower.DataBind();
ViewState["Sort"] = 0;
}
}
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = towers.CopyToDataTable();
gridviewTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
Session["GridView"] = GridViewTower.DataSource;
}
You don't need to store whole table in the Session or ViewState. Just store values of SortExpression, SortOrder etc. Here's an example how you can do it.
In my code I have added two private properties to store sortorder and sortexpression:
private string SortOrder
{
get
{
// Toggle order after sorting
string _order = "ASC";//Default
if( ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() =="DESC")
{
_order = "DESC";
ViewState["SortOrder"] = "ASC";
}
else
{
ViewState["SortOrder"] = "DESC";
}
return _order;
}
set
{
string _order = value.ToLower() == "descending"? "DESC" : "ASC";
ViewState["SortOrder"] = _order;
}
}
private string SortExpression
{
get
{
return ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : "";
}
set
{
ViewState["SortExpression"] = value;
}
}
I have changed your GridView_Sort method to store the sort expression and sort order in newly added properties and called LoadData() method:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
SortExpression = e.SortExpression;
//Disabled sort direction to enable toggling
//SortOrder = e.SortDirection.ToString();
LoadData();
}
The LoadData() method will be called from many places, whenever we want to load data into GridView. So I have changed it to this:
public void LoadData()
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = new DataTable();
gridviewTable.Columns.Add("TowerId");
gridviewTable.Columns.Add("TowerName");
gridviewTable.Columns.Add("rangeName");
foreach (var t in towers)
{
gridviewTable.Rows.Add(new object[] { t.TowerId, t.TowerName, t.rangeName });
}
if (!String.IsNullOrEmpty(SortExpression))
{
gridviewTable.DefaultView.Sort = String.Format("{0} {1}", SortExpression, SortOrder);
gridviewTable = gridviewTable.DefaultView.ToTable();
}
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
}
Initially I call the LoadData() method in Page_Load() :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
You can download the test project here.

To solve an exception details in web site creation

I am creating a web site but anytime I run this code, an exception is raised:
#Exception Details: System.IndexOutOfRangeException: There is no row at position 0.
How do I solve this problem?
public partial class Employee_frmSearchClaims : System.Web.UI.Page
{
int empno;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["empno"] != null)
empno = int.Parse(Session["empno"].ToString());
if (!IsPostBack)
{
DataRow r = AddPoliciesOnEmployees.GetPolicyOnEmployee(empno).Tables[0].Rows[0];
Label7.Text = r["policyname"].ToString();
Label8.Text = r["policyid"].ToString();
Label9.Text = r["policyamount"].ToString();
Label10.Text = r["TotalAmount"].ToString();
Label11.Text = r["pstartdate"].ToString();
}
}
protected void btnapplicy_Click(object sender, EventArgs e)
{
if (ddlReason.SelectedItem.ToString() != "--Select--")
{
if (ddlReason.SelectedItem.Text == "Death")
{
Session["Reason"] = ddlReason.SelectedItem.Text;
Response.Redirect("frmDeathCliam.aspx");
}
else if (ddlReason.SelectedItem.Text == "Accident")
{
Session["Reason"] = ddlReason.SelectedItem.Text;
Response.Redirect("frmAccidentClaim.aspx");
}
else
{
Session["Reason"] = ddlReason.SelectedItem.Text;
Response.Redirect("frmCompleteClaim.aspx");
}
}
else
lblmsg.Text = "You have to select the reason";
}
}
You need to make sure your table contains rows first:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["empno"] != null)
empno = int.Parse(Session["empno"].ToString());
if (!IsPostBack)
{
var ds = AddPoliciesOnEmployees.GetPolicyOnEmployee(empno);
if (ds.Tables[0].Rows.Count > 0)
{
DataRow r = ds.Tables[0].Rows[0];
Label7.Text = r["policyname"].ToString();
Label8.Text = r["policyid"].ToString();
Label9.Text = r["policyamount"].ToString();
Label10.Text = r["TotalAmount"].ToString();
Label11.Text = r["pstartdate"].ToString();
}
}
}

if i am deleting a row(ipaddress) in 2nd page of gridview it is deleting the first row in firstpage

\mycode
protected void btnRemove_Click(object sender, EventArgs e)
{
try
{
Button lbl = (Button)sender;
GridViewRow gv = (GridViewRow)lbl.NamingContainer;
int rowID = gv.RowIndex - 1;
if (ViewState["dt"] != null)
{
DataTable dt = (DataTable)ViewState["dt"];
// if (dt.Rows.Count > 1)
//{
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[gv.RowIndex]);
// }
//Store the current data
ViewState["dt"] = dt;
//Re bind the GridView for the updated data
gridIP.DataSource = dt;
gridIP.DataBind();
hdnCount.Value = gridIP.Rows.Count.ToString();
HidingRowID();
if (gridIP.Rows.Count == 0)
{
ReqFromIP.Enabled = true;
ValreqFromIP.Enabled = true;
ReqToIP.Enabled = true;
ValreqToIP.Enabled = true;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Plese specify at least one IP Range." + "');", true);
}
else
{
ReqFromIP.IsValid = true;
ReqFromIP.Enabled = false;
ValreqFromIP.Enabled = false;
ReqToIP.IsValid = true;
ReqToIP.Enabled = false;
ValreqToIP.Enabled = false;
}
}
}
catch (Exception ex)
{
Logging.LogExeption(ex);
}
}
protected void gridIP_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridIP.PageIndex = e.NewPageIndex;
gridIP.DataSource = (DataTable)ViewState["dt"];
gridIP.DataBind();
}

Categories

Resources