GridVIew does not refresh after paging - asp.net

My GridView is populated with a certain filter criteria.
I have PageIndexChanging event to perform pagination of my data.
protected void gvPeople_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
lblAddError.Text = String.Empty;
List<People> list = (List<People>)ViewState[_vsPeopleList];
gvPeople.DataSource = list;
gvPeople.PageIndex = e.NewPageIndex;
gvPeople.EditIndex = -1;
gvPeople.DataBind();
}
After that I perfrom Search without changing the filter criteria.
protected void btnPeopleSearch_Click(object sender, CommandEventArgs e)
{
if(e.CommandName.Equals("Search"))
{
PopulatePeople();
}
}
private void PopulatePeople()
{
lblAddError.Text = String.Empty;
if (ViewState["_message"] != null)
{
lblAddError.Visible = true;
lblAddError.Text = ViewState["_message"].ToString();
}
ViewState["_message"] = null;
int portfolio = int.Parse(ddlPortfolio.SelectedItem.Value);
ViewState["portfolioID"] = portfolio;
string year = ddlYear.SelectedItem.Text;
string month = ddlMonth.SelectedItem.Text;
List<People> list = People.GetPeople(portfolio, year, month);
ViewState[_vsPeopleList] = list;
if(list.Count == 0)
{
gvPeople.Visible = false;
lblAddError.Visible = true;
lblAddError.Text = "No data available for current selection";
}
else
{
gvPeople.Visible = true;
gvPeople.DataSource = list;
gvPeople.DataBind();
}
}
I'm supposed to get all the data in the GridView as I had before paging to the next page. However, my page does not refresh to show all the data, it only shows the data for that page index, however, my list has count equals to the number of records populated from the database. Also, if I change search filter, data is displayed correctly.
What am I doing wrong?

Looks like the gvHolidays_PageIndexChanging event is related to some other grid as the code written within it is for grid gvPeople.
If not, then try the following.
//Write the following code inside gridviews PageIndexChanging event.
gvPeople.PageIndex = e.NewPageIndex;
gvPeople.EditIndex = -1;
gvPeople.SelectedIndex = -1;
//Write the following code inside gvHolidays_PageIndexChanged event.
lblAddError.Text = String.Empty;
List<People> list = (List<People>)ViewState[_vsPeopleList];
gvPeople.DataSource = list;
gvPeople.DataBind();

Related

Sorting Data gridview by clicking header in asp.net

Please help me to sort the data in a grid view by clicking header in asp.net. i have used linq for bind data to gridview. Please help me.
You can do it very easily.
So lets say you have a GridView, to which you assign the datasource at the server side.
you can make use of GridView_Sorting event, some thing like given below:
firstly, save the current applied sort somewhere. because, you need to know, whether you have to sort ascending or descending. something like below.
public SortDirection CurrentSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
and then use this property inside the sorting event of the GridView:
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
if (CurrentSortDirection== SortDirection.Ascending)
{
CurrentSortDirection = SortDirection.Descending;
var myDataSource = GetDataThroughLinq()
.OrderByDescending(s=>s.Id)
.ToList();
GridView1.DataSource = myDataSource;
GridView1.DataBind();
}
else
{
CurrentSortDirection = SortDirection.Ascending;
var myDataSource = GetDataThroughLinq()
.OrderBy(s=>s.Id)
.ToList();
GridView1.DataSource = myDataSource;
GridView1.DataBind();
}
}
You can directly choose a datasource for the gridview, its in gridview tasks just below the auto format, after selecting datasouce more option is provided it includes sorting, paging and selection too, and by clicking on every heading, you will get the data sorted according to it
Try this for sorting.....
protected void RadgvData_SortCommand(object sender, GridSortCommandEventArgs e)
{
GridTableView tableView = e.Item.OwnerTableView;
e.Canceled = true;
GridSortExpression expression = new GridSortExpression();
expression.FieldName = e.SortExpression;
if (tableView.SortExpressions.Count == 0 || tableView.SortExpressions[0].FieldName != e.SortExpression)
{
expression.SortOrder = GridSortOrder.Descending;
}
else if (tableView.SortExpressions[0].SortOrder == GridSortOrder.Descending)
{
expression.SortOrder = GridSortOrder.Ascending;
}
else if (tableView.SortExpressions[0].SortOrder == GridSortOrder.Ascending)
{
expression.SortOrder = GridSortOrder.Descending;
}
tableView.SortExpressions.AddSortExpression(expression);
RadgvData.Rebind();
}

LinkButton in GridView not picking correct value

I am using link button to display a pdf report for selected Report Id from Grid view. On page load I am binding the datasource with Gridview. By clicking the link button it fetches the correct report id from column 0 and displays the report. After sorting the grid the grid view shows the sorted data. Now if i click the link button it is not picking the changed value from column 0. instead it is picking the value before sorted.
Say: Column 0 has values 1, 2, 3, 4, 5 before sorting. If i click link button of Row 3 before sorting it is picking value 3 from column 0. After sorting it is 3,4,5,2,1. Now if i click link button of row 3 it is still picking value 3 instead of 5. Can you please help me.
Below is my code:
aspx:
CS:
protected void Page_Load(object sender, EventArgs e)
{
bindGrid();
}
protected void GvStockTakingReport_Sort(object sender, GridViewSortEventArgs e)
{
GvStockTakingReport.DataSource = null;
GvStockTakingReport.DataBind();
GvStockTakingReport.Dispose();
DataSet ds = StockTakingList.BindStocktakingReportGrid();
DataTable dtSortTable = ds.Tables[0];
if (dtSortTable != null)
{
DataView dv = new DataView(ds.Tables[0]);
dv.Sort = e.SortExpression + " " + getSortDirectionString();
//ViewState["sortExpression"] = e.SortExpression;
//Session["sortExpression"] = e.SortExpression;
GvStockTakingReport.DataSource = dv;
GvStockTakingReport.DataBind();
}
}
protected void PrintReport(object sender, CommandEventArgs e)
{
LinkButton lkButton = (LinkButton)sender;
GridViewRow item = (GridViewRow)lkButton.NamingContainer;
string Id = (item.FindControl("lblstk_id") as Label).Text;
//Getting value for Id
string Id1 = e.CommandArgument.ToString();
int rowIndex = Convert.ToInt32((string)e.CommandArgument);
//string Id1 = Convert.ToString(GvStockTakingReport.Rows[rowIndex].Cells[0].Text);
string Id2 = ((Label)(GvStockTakingReport.Rows[rowIndex].FindControl("lblstk_id"))).Text;
//Getting value for Id
string virtualPath = string.Format("~/{0}/{1}{2}", Portal.Business, Portal.Core.Profile.ReportsDirectory, "General/RPT_03002_StockTakinReport.rpt");
string physicalPath = Server.MapPath(virtualPath);
using (ReportDocument report = new ReportDocument())
{
report.Load(physicalPath);
Core.Security.CrystalReportLogOn(report, (SqlConnectionStringBuilder)Portal.Core.Profile.ConnectionStrings["MTServer"]);
report.SetParameterValue("#STK_Id", Id);
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Page.Response, true, "Stock Taking report");
}
}
the issue was whenever i click the link button the page load calls
bindgrid method which resets the gridview to original sorting before the printreport method invokes.
I have included the sorting logic in bindgrid method as well as below which resolved the issue.
public void bindGrid()
{
try
{
DataSet ds = StockTakingList.BindStocktakingReportGrid();
GvStockTakingReport.DataSource = ds;
GvStockTakingReport.DataBind();
//To make sure the grid remains with sorting order while pageload method invokes otherwise it will reset to original order
DataView dv = new DataView(ds.Tables[0]);
if (dv != null)
{
if (ViewState["sortExpression"] == null)
{
ViewState["sortExpression"] = "STK_Id"; //First time it will sort by STK_ID i.e on first time page loading
}
if (ViewState["sortDirection"] == null)
{
ViewState["sortDirection"] = "ASC";//First time it will sort ascending i.e on first time page loading
}
dv.Sort = ViewState["sortExpression"].ToString() + " " + ViewState["sortDirection"].ToString();
GvStockTakingReport.DataSource = dv;
GvStockTakingReport.DataBind();
}
}
catch (Exception ex)
{
error.Visible = true;
error.Text = ex.Message.ToString();
}
}

Gridview paging Show all Records

i have a gridview that has paging enabled. i also have a dropdown on the pager of the gridview where the user can select how many records per page they would like to retrieve. Once the dropdown is changed then an event is fired (shown below) to rerun the query with the updated results per page request. This works very well. I did however want to have a value "All" on the dropdown aswell and the method i used to impliment this is by disabling paging.
This all works brilliantly except for one issue. When the user selects "All" on the dropdown i would like to still show the pager once the gridview is updated. It doesnt show because i turned off paging but is there a way to show the pager again? See my code below for the event. (As you can see i renable the pager at the end but this has no effect)
thanks
damo
Code behind Event for Dropdown Change
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.AllowPaging = false;
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
Result fAuditOverallStatusLatest = new Result(sConn);
GridViewMain.DataSource = Result.getAuditOverallStatusLatest();
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
GridViewMain.BottomPagerRow.Visible = true;
GridViewMain.TopPagerRow.Visible = true;
}
DDL Code behind
protected void GridViewMain_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList GridViewMainddl = new DropDownList();
//adds variants of pager size
GridViewMainddl.Items.Add("5");
GridViewMainddl.Items.Add("10");
GridViewMainddl.Items.Add("20");
GridViewMainddl.Items.Add("50");
GridViewMainddl.Items.Add("100");
GridViewMainddl.Items.Add("200");
GridViewMainddl.Items.Add("500");
GridViewMainddl.Items.Add("All");
GridViewMainddl.AutoPostBack = true;
//selects item due to the GridView current page size
ListItem li = GridViewMainddl.Items.FindByText(GridViewMain.PageSize.ToString());
if (li != null)
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
GridViewMainddl.SelectedIndexChanged += new EventHandler(GridViewMainddl_SelectedIndexChanged);
//adds dropdownlist in the additional cell to the pager table
Table pagerTable = e.Row.Cells[0].Controls[0] as Table;
TableCell cell = new TableCell();
cell.Style["padding-left"] = "15px";
cell.Controls.Add(new LiteralControl("Page Size:"));
cell.Controls.Add(GridViewMainddl);
pagerTable.Rows[0].Cells.Add(cell);
//add current Page of total page count
TableCell cellPageNumber = new TableCell();
cellPageNumber.Style["padding-left"] = "15px";
cellPageNumber.Controls.Add(new LiteralControl("Page " + (GridViewMain.PageIndex + 1) + " of " + GridViewMain.PageCount));
pagerTable.Rows[0].Cells.Add(cellPageNumber);
}
}
Put this in your Page_Init:
GridViewMain.PreRender += new EventHandler(GridViewMain_PreRender);
Then elsewhere in your Page class:
void GridViewMain_PreRender(object sender, EventArgs e)
{
var pagerRow = (sender as GridView).BottomPagerRow;
if (pagerRow != null)
{
pagerRow.Visible = true;
}
}
Then for your drop down event:
void GridViewMainddl_SelectedIndexChanged(object sender, EventArgs e)
{
MyServices fServices = new FAServices(sConn);
Result fAuditOverallStatusLatest = new Result(sConn);
var data = Result.getAuditOverallStatusLatest();
//changes page size
if ((((DropDownList)sender).SelectedValue).ToString() == "All")
{
GridViewMain.PageSize = data.Count();
}
else
{
GridViewMain.PageSize = int.Parse(((DropDownList)sender).SelectedValue);
}
//binds data source
GridViewMain.DataSource = data;
GridViewMain.PageIndex = 0;
GridViewMain.DataBind();
GridViewMain.AllowPaging = true;
}
In that PreRender event, you'll have to duplicate that code for the top pager.
Edit: To get All selected, make this change in GridViewMain_RowCreated:
if (li != null)
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.IndexOf(li);
}
else
{
GridViewMainddl.SelectedIndex = GridViewMainddl.Items.Count - 1;
}

Gridview showing up deleted datas

I just display my uploaded file details in my GridView, so there will be only one row in my GridView - multiple files are not allowed.
When I delete that single row and try to upload a new file, it is showing 2 rows (the new file and the deleted file).
I already tried using GridView.DataSource = null and GridView.DataBind().
Note: I've rebinded my GridView after the delete, but it still shows the deleted file.
protected void DeleteLinkButton_Click(object sender, EventArgs e)
{
if (Session["name"] != null)
{
string strPath = Session["filepath"].ToString();
System.IO.File.Delete(strPath);
GridView2.Rows[0].Visible = false;
Label8.Text = "";
Session["filename"] = null;
Button3.Enabled = true;
}
GridView2.DataBind();
}
In some cases I've had to do something like this:
//page level variable
bool refreshRequired = false;
protected void DeleteLinkButton_Click(object sender, EventArgs e)
{
if (Session["name"] != null)
{
string strPath = Session["filepath"].ToString();
System.IO.File.Delete(strPath);
GridView2.Rows[0].Visible = false;
Label8.Text = "";
Session["filename"] = null;
Button3.Enabled = true;
refreshRequired = true;
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(refreshRequired)
{
//whatever you to to set your grids dataset, do it here
//but be sure to get the NEW data
}
}
At the time of Delete, your grid is bound to the old data. When you change the data, you must rebind it to the new.

how to retain the value of global string variable even after page load in asp.net

I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:
public partial class Caravan_For_Sale : System.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = null;
switch (check)
{
case "0-1500":
break;
case "1500-2000":
dt = caravans.GetFilterbyPrice1();
break;
case "2000+":
break;
default:
dt = caravans.GetAllCaravans();
break;
}
// DataTable dt = caravans.GetAllCaravans();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
DataList1.RepeatColumns = 3; // 4 items per line
DataList1.RepeatDirection = RepeatDirection.Horizontal;
DataList1.DataSource = pds;
DataList1.DataBind();
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
doPaging();
}
protected void lnkPrice2_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
check = _sender.CommandArgument;
// items["test"] = test;
DataTable dt = caravans.GetFilterbyPrice2();
if (dt.Rows.Count < 3)
{
lnkbtnNext.Enabled = false;
lnkbtnPrevious.Enabled = false;
}
CurrentPage = 0;
BindGrid();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated
As far as I know, you have two options:
1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.
2) Put it in the ViewState just like this:
ViewState["check"] = check;
And load it after with this:
string check = Convert.ToString(ViewState["check"]);
Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.
For example
ViewState("Variable") = "Your string"
Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.

Resources