GridView PageIndexChanging event - asp.net

I have a gridview for which I set the boundfields as well as the datasource in code behind and on the PageIndexChanging event I set:
protected void grvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grvList.PageIndex = e.NewPageIndex;
grvList.DataBind();
}
BoundFields are also coming from the database, I have added them like this:
foreach (DataRow drColumn in dtColumns.Rows)
{
BoundField bfEmbeddedColumn = new BoundField();
bfEmbeddedColumn.HeaderText = drColumn["ColName"].ToString();
bfEmbeddedColumn.DataField = drEmbeddedTaskColumn["ColName"].ToString();
bfEmbeddedColumn.ItemStyle.Width = 120;
grvList.Columns.Add(bfEmbeddedColumn);
}
It does show the records on the next page, but my problem is that each time the page index is changed it add the boundfields again. How can I prevent this from happening, it there a way I can solve this issue?
Thank you very much.

you have to move the following index to the variable e to the pager.
try this:
grdSqlQuery.PageIndex = e.NewPageIndex
grdSqlQuery.DataSource = ViewState("dts_Sqlquery")
grdSqlQuery.DataBind()

protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
try
{
int count = 0;
SetData();
GridView1.AllowPaging = false;
GridView1.DataBind();
ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
count = arr.Count;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (arr.Contains(GridView1.DataKeys[i].Value))
{
Session.Add("PatientID", GridView1.DataKeys[i].Value.ToString());
arr.Remove(GridView1.DataKeys[i].Value);
Response.Redirect("~/EditPaitientDetails.aspx");
}
}
ViewState["SelectedRecords"] = arr;
hfCount.Value = "0";
GridView1.AllowPaging = true;
BindGrid();
//ShowMessage(count);
}
catch (Exception ex)
{
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}

Found the solution to this. My problem was caused by the fact that on Page_Load I was adding the boundfields over and over again.

Related

Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount

i want to bind my data Gridview but it throw an error.
i allow paging when i click on new page e.g 1.2.3 then the above error throw
here is my code.
the one is page index change and the other one is my method of BindGrid.
the error come when i click one new page 2 or 3 etc
updated code
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
DataGrid1.DataSource = Session["data"] as DataTable;
DataGrid1.DataBind();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days, CaseTypeID, CollectorID, user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
Session["data"] = data;
DataGrid1.DataSource = data;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
Problem what is happening is when you fetch the data again in BindGrid() method you must be getting less number of pages.so you can do two things.
1)If you are filtering your data then reset the page index to 1.
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
BindGrid();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days,CaseTypeID,CollectorID,user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
DataGrid1.DataSource = data;
DataGrid1.CurrentPageIndex = 0;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
2)If you are not filtering your data then store the datagrid value in a session object and use this for pageing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
DataGrid1.DataSource = Session["value"] as DataTable;
DataGrid1.DataBind();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days,CaseTypeID,CollectorID,user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
Session["value"]=data;
DataGrid1.DataSource = data;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
DataGrid1.DataSource = data;
DataGrid1.DataBind();
DataGrid1.CurrentPageIndex = 0;
Reset the CurrentPageIndex to 0 after the page has been bound.

PageIndexChanging Event in search button in asp.net?

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid();
}
}
protected void btnsearch_Click(object sender, EventArgs e)
{
objRetailPL.ZoneName = ddlzone.SelectedValue;
//IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
//String datetime = txtdate.Text.ToString();
//DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
//objRetailPL.date =dt;
DataTable dtsearch = new DataTable();
dtsearch = objRetailBAL.searchzone(objRetailPL);
GVRate.DataSource = dtsearch;
GVRate.DataBind();
}
protected void GVRate_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GVRate.PageIndex = e.NewPageIndex;
grid();
}
catch (Exception ex)
{
}
}
I have this code for searching records.And for that grid i added page index,but it is not coming properly.When click on search button it is showing more n of records at that time page index is not working. It is calling First grid before clicking search button..How can I change my code please help me.....
Try this ...
private void grid()
{
if(!string.IsNullOrEmpty(yourSearchTextBox.Text)
{
// Then call search method. Make sure you bind the Grid in that method.
}
else
{
// Normally Bind the Grid as you are already doing in this method.
}
}
you have to check whether there is any search Text or not in that grid() method like...

Adding a checkbox in a table cell

Is this possible?
I have a table with user accounts retrieved from a database. Then at the start of each column I would like to add a checkbox which if selected will select the account. I tried experimenting with it and I can't seem to put the checkbox inside the table. How can I do this?
You can try this:
const int ColumnSelect = 0;
protected void Page_Load(object sender, EventArgs e)
{
//Get real data here.
DataTable dt = new DataTable();
dt.Columns.Add("count");
dt.Rows.Add(dt.NewRow());
dt.Rows[0][0] = "5";
GridView1.Columns.Add(new TemplateField());
BoundField b = new BoundField();
GridView1.Columns.Add(b);
b.DataField = "count";
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
e.Row.Cells[ColumnSelect].Controls.Add(new CheckBox());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in GridView1.Rows)
{
//Could also use (CheckBox)row.Cells[ColumnSelect].FindControl if you give the checkboxes IDs when generating them.
CheckBox cb = (CheckBox)row.Cells[ColumnSelect].Controls[0];
if (cb.Checked)
{
//Do something here.
}
}
}

Result cannot be changed upon changing gridview page number

When I was changing page number, I was getting error
"The GridView 'GridView1' fired event PageIndexChanging which wasn't handled."
But afterwards, I searched and try to put this code in PageIndexChanging even, still it isn't working :
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.SelectedIndex = e.NewPageIndex;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
Originally, when user prompts to page, I am showing all data on gridview, then user can search data, and upon clicking Search button, below code is executing :
protected void Button1_Click(object sender, EventArgs e)
{
DateTime dt1 = DateTime.Now, dt2 = DateTime.Now;
Connection.getCon();
try
{
dt1 = Convert.ToDateTime(TextBox3.Text);
dt2 = Convert.ToDateTime(TextBox4.Text).AddDays(1);
lblError.Visible = false;
}
catch (Exception exc) {
lblError.Visible = true;
}
string cmd = "select * from tblLogs where (users like '%"+TextBox1.Text.Trim()+"%') and (request like '%"+TextBox2.Text.Trim()+"%') and (requesttime>='"+dt1+"') and (requesttime<'"+dt2+"') ";
SqlDataSource1.SelectCommand = cmd;
DataView dv= (DataView) SqlDataSource1.Select(DataSourceSelectArguments.Empty);
GridView1.DataSourceID = null;
GridView1.DataSource= dv;
GridView1.DataBind();
//GridView1.AllowPaging = false;
}
Now, I am not getting any error, but still page is not changing and staying on 1.
Thanks.
You are using the wrong property in your PageIndexChanging event, it should be PageIndex instead of SelectedIndex:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}

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