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

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.

Related

Cant Get Data To Return To My Grid View Using Linq in ASP.NET

Not sure why but i cant get my data to return. It starts out saying there is not data records to display. But when i select the month and year of the information i am looking for the grid view disappears. Any suggestions
NutritionEntities context;
protected void Page_Load(object sender, EventArgs e)
{
context = new NutritionEntities();
if (!IsPostBack)
{
for (int i = DateTime.Now.Year; i > 1988; i--)
{
ddlYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
you have verify the binding of your control grid, i suggest add only object to the datasource of the grid on the pageLoad when the postback its false like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
}
GridView1.DataBind();
}
the problem is when you add the objects to datasource , when any event refresh the web page like select the control is unbinding, i hope help you,, see you!!

ASP.NET, Code on click of a next button

The following is my code, I am doing project on online examination in that I have a module of question to display in this when I click on next button it should go to the next question but it is not going.
public partial class Student : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
int i=1;
Session["Number"] = i;
protected void Page_Load(object sender, EventArgs e)
{
Session["Number"] = i++;
Label1.Text = Session["Number"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Questions where QuestionNo = '"+Label1.Text+"'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label2.Text = dr["Question"].ToString();
Label3.Text = dr["Ans1"].ToString();
Label4.Text = dr["Ans2"].ToString();
Label5.Text = dr["Ans3"].ToString();
Label6.Text = dr["Ans4"].ToString();
}
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from Answers where QuestionNo = '" + Label1.Text + "'", con);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
Label8.Text = dr1["Answer"].ToString();
}
con.Close();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Label7.Text = Label3.Text;
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
Label7.Text = Label4.Text;
}
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
Label7.Text = Label5.Text;
}
}
protected void RadioButton4_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton4.Checked)
{
Label7.Text = Label6.Text;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Label7.Text == Label8.Text)
{
Label9.Text = "Your Answer is correct";
}
else
Label9.Text = "Your Answer is incorrect";
}
protected void Button2_Click(object sender, EventArgs e)
{
i++;
Session["Number"] = i;
Response.Redirect("Student.aspx");
}
}
So many bad things in this code.
You should always give names to your variables properly.
Don't concatenate SQL queries because security reasons like SQL Injection
You should use Session["Number"] to select the question number rather than Label1.Text.
Use session when it was only necessary.
First thing that you are doing wrong is how you are trying to store value of i in your Session. You are overwriting it every time you get into the method and thus resulting in same question number on each button click.
Second, you should parametrized your queries.
On each button click you should retrieve the value of i from your session and then increment it and again store it in the session. like:
int i = 0;
if (Session["Number"] == null)
{
Session["Number"] = i;
}
else
{
i = Convert.ToInt32(Session["Number"]);
}
//Later To increment Session
Session["Number"] = ++i; //First increments, then assigns the value
You should also use ++i instead of i++ since that will store the value of i before increment.

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();
}

GridView PageIndexChanging event

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.

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.

Resources