Problem with page lifecycle - asp.net

The qustion was modified by me to show a complete picture.
I have a basic question:
code behind:
protected void Page_Load(object sender, EventArgs e)
{
int firstPageIndex = 0;
int lastPageIndex = 5;
if (TotalPageNumber > 5)
{
if ((TotalPageNumber - PageIndex) <= 5)
firstPageIndex = TotalPageNumber - 5;
firstPageIndex = PageIndex < 3 ? 0 : PageIndex - 2;
}
else
{
firstPageIndex = 0;
lastPageIndex = TotalPageNumber;
}
for (int i = firstPageIndex; i < firstPageIndex + lastPageIndex; i++)
{
LinkButton lnk = new LinkButton();
lnk.CommandArgument = i.ToString();
lnk.Click += new EventHandler(lblPageNumber_Click);
lnk.ID = "lnkPage" + (i + 1).ToString();
lnk.Text = (i + 1).ToString();
plcPagerHolder.Controls.Add(lnk);
} }
int _pageIndex;
public int PageIndex
{
get
{
object objPage = ViewState["_pageIndex"];
if (objPage == null)
{
_pageIndex = 0;
}
else
{
_pageIndex = (int)objPage;
}
return _pageIndex;
}
set {ViewState["_pageIndex"] = value; }
}
protected void lnkPagerNext_Click(object sender, EventArgs e)
{
PageIndex = PageIndex == TotalPageNumber - 1 ? 0 : PageIndex + 1;
}
The problem is with Page_Load event, I expect to get new PageIndex after the linkbutton is clicked.
Update:
My Foo adds new controls to the page, based on provide Page index so I guess I can't put it in Prerender.

Two options
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Foo (PageIndex);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
PageIndex = int.Parse(((LinkButton)sender).CommandArgument);
Foo (PageIndex);
}
or
protected void Page_PreRender(object sender, EventArgs e)
{
Foo (PageIndex);
}

you can place Foo (PageIndex) in Page_LoadComplete event instead of Page_Load, i.e.
protected void Page_LoadComplete(object sender, EventArgs e)
{
Foo (PageIndex);
}
LoadComplete event is raised after Control events.
Edit:
LoadComplete is the earliest place where you can safely access new pageindex and also you can add there another controls, but that is possible also in PreRender.

And you will, but Page_Load gets called before the event handler for the linkbutton .. so, you can't really expect it to be changed yet.

Related

How do I add a variable for the textbox ID inside a function?

public partial class _Default : System.Web.UI.Page
{
double[] array = new double[5];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<5;i++)
{
array[i] = Convert.ToDouble(TextBox(i+1).Text);
}
}
}
This is my code, I have 5 textboxes, I'd like to refer to them with the int (i) inside the loop.
array[i] = Convert.ToDouble(TextBox(i+1).Text);
the text boxes are named 'TextBox1' , 'TextBox2', 'TextBox3, etc.
Is it possible in C#?
You could if you use Control.FindControl
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
TextBox currenTextBox = (TextBox) FindControl("TextBox" + i);
if (!string.IsNullOrEmpty(currenTextBox?.Text))
{
if (double.TryParse(currenTextBox.Text, out var result))
{
array[i] = result;
}
}
}
}

How to prevent to adding two lists in asp.net?

How to Prevent adding two controls or to lists ? I've tried this code but it doesn't work... Pease help!
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ViewState["check"] = "First_Time";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["check"] == "First_Time")
{
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
ViewState["check"] = "Scond_Time";
}
else
{
Response.Write("Sorry, Can't create a list on second time");
}
}
The problem with your approach is that the button click event is triggered on postback, hence your postback check in Page_Load is pointless.
Since the CheckBoxList.Items are stored in Viewstate by default(it implements IStateManager), why don't you simply check if the items are already added?
protected void Button1_Click(object sender, EventArgs e)
{
if (CheckBoxList1.Items.Count < 6)
{
CheckBoxList1.Items.Clear();
for (int i = 0; i < 6; i++)
{
CheckBoxList1.Items.Add(i.ToString());
}
}
else
{
// don't use Response.Write to output messages but controls
Response.Write("Sorry, Can't create a list on second time");
}
}

Getting the index of the last row inserted in a GridView

How do I get the row index of the last row inserted in a GridView considering the user may have custom ordering in the grid (I can't use the last row).
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
GridViewCompleteWidget.EditIndex = ??????;
}
I want to put the row into edit mode immediately after the insert occurs.
UPDATE
protected void ButtonAdd_Click(object sender, EventArgs e)
{
//SqlDataSourceCompleteWidget.InsertParameters.Add("EFFECTIVE_DATE", Calendar1.SelectedDate.ToString("yyyy-MM-dd"));
SqlDataSourceCompleteWidget.InsertParameters[0].DefaultValue = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
GridViewCompleteWidget.EditIndex = 1;
}
private int mostRecentRowIndex = -1;
protected void GridViewCompleteWidget_RowCreated(object sender, GridViewRowEventArgs e)
{
mostRecentRowIndex = e.Row.RowIndex;
//GridViewCompleteWidget.EditIndex = e.Row.RowIndex;
}
You would want to handle the RowCreated event. You can access the row data and identity/location using the GridViewRowEventArgs object that is passed to this event handler.
void YourGridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
YourGridView.EditIndex = e.Row.RowIndex;
}
Edit using the gridview's onitemcommand. Then you can use a binding expression on the grid column to set whatever you want. If you are using a button or linkbutton or several others you could use the CommandArgument
CommandArgument='<%# Eval("DataPropertyIWant") %>'
Edit
Sorry I skipped that ordering was done by user. I've tested the following code and it works having respected the users ordering of items, but we must take the user to the page where the last row exists.
1st: Retrieve the Max(ID) from database after insertion, store it in a session
select Max(ID) from tbl_name; -- this statement can retrieve the last ID
Session["lastID"]=lastID;
2nd:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
if (Session["lastID"] != null)
if ((int)DataBinder.Eval(e.Row.DataItem, "ID") == (int)Session["lastID"])
{
//Session["rowIndex"] = e.Row.RowIndex;
int rowIndex=e.Row.RowIndex;
if (Session["type"] != null)
if (Session["type"].ToString() == "Normal")
{
int integ;
decimal fract;
integ = rowIndex / GridView1.PageSize;
fract = ((rowIndex / GridView1.PageSize) - integ;
if (fract > 0)
GridView1.PageIndex = integ;
else if (integ > 0) GridView1.PageIndex = integ - 1;
GridView1.EditIndex = rowIndex;
}
}
}
3rd: Convert your commandField into TemplateFields and Set their CommandArgument="Command"
I'll use this argument to identify what triggered RowDataBound event. I store the value in a Session["type"]. The default value is "Normal" defined in the page load event.
if(!IsPostBack)
Session["type"]="Normal";
the other value is set in RowCommand event
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandArgument == "Command")
Session["type"] = "Command";
}
It works for me fine.
Sorry for my language and,may be, unnecessary details.
UPDATE: I worked off of this post
I'm assuming you just return a value after doing the insert but you can set ID wherever you insert the record.
private int mostRecentRowIndex = -1; //edit index
private bool GridRebound = false; //used to make sure we don't rebind
private string ID; //Is set to the last inserted ID
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//Set so grid isn't rebound on postback
GridRebound = true;
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.InsertParameters[0].DefaultValue = Calendar1.SelectedDate.ToString("yyyy-MM-dd");
ID = SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.DataBind();
}
protected void GridViewCompleteWidget_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Check that the row index >= 0 so it is a valid row with a datakey and compare
//the datakey to ID value
if (e.Row.RowIndex >= 0 && GridViewCompleteWidget.DataKeys[e.Row.RowIndex].Value.ToString() == ID)
{
//Set the edit index
mostRecentRowIndex = e.Row.RowIndex;
}
}
protected void GridViewCompleteWidget_DataBound(object sender, EventArgs e)
{
//Set Gridview edit index if isn't -1 and page is not a post back
if (!GridRebound && mostRecentRowIndex >= 0)
{
//Setting GridRebound ensures this only happens once
GridRebound = true;
GridViewCompleteWidget.EditIndex = mostRecentRowIndex;
GridViewCompleteWidget.DataBind();
}
}
Selects if inserting last record in gridview (no sorting)
You should be able to get the number of rows from the datasource: (minus 1 because the rows start at 0 and the count starts at 1)
GridViewCompleteWidget.EditIndex = ((DataTable)GridViewCompleteWidget.DataSource).Rows.Count - 1;
But put this before you bind the data:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlDataSourceCompleteWidget.Insert();
GridViewCompleteWidget.EditIndex = ((DataTable)GridViewCompleteWidget.DataSource).Rows.Count - 1;
GridViewCompleteWidget.DataBind();
}

How to preserve dynamically created controls?

I want to preserve the dynamically created control when postback occurs .
protected void Page_Load(object sender, EventArgs e)
{
}
private void CreateTable()
{
HtmlTableRow objHtmlTblRow = new HtmlTableRow();
HtmlTableCell objHtmlTableCell = new HtmlTableCell();
objHtmlTableCell.Controls.Add(new TextBox());
objHtmlTblRow.Cells.Add(objHtmlTableCell);
mytable.Rows.Add(objHtmlTblRow);
this.SaveControlState();
// this.Controls.Add(mytable);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTable();
}
It can be achieved by calling CreateTable() in Page_Load. Is there any alternative way to preserve the control
Thanks
You can add them to a List when you create them and save your List to Session. On postback (Page_Load) load them from your Session to your Page.
the below code should work
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateTable()
}
public static Control GetPostBackControl(Page thisPage)
{
Control ctrlPostedback = null;
string ctrlName = thisPage.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
{
ctrlPostedback = thisPage.FindControl(ctrlName);
}
else
{
foreach (string Item in thisPage.Request.Form)
{
Control c = thisPage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
ctrlPostedback = c;
}
}
}
return ctrlPostedback;
}
The code works from UpdatePanel
Reference:http://www.asp.net/ajax/videos/how-to-dynamically-add-controls-to-a-web-page

Control Add PostBack Problem

I Add Control Dynamiclly but; easc Postback event my controls are gone. I Can not see again my controls.
So How can I add control ?
Because you must recreate your controls on every postback,
see this article
Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.
See this link...
ASP.NET Add Control on postback
A very trivial example..
public partial class MyPage : Page
{
TextBox tb;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
tb = new TextBox();
tb.ID = "testtb";
Page.Form.Controls.Add(tb);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//tb.Text will have whatever text the user entered upon postback
}
}
You should always assign a unique ID to the UserControl in its ID property after control is loaded. And you should always recreate UserControl on postback.
To preserve posback data (i.e. TextBox'es) you must load UserControl in overriden LoadViewState method after calling base.LoadViewState - before postback data are handled.
Add controls in runtime and save on postback:
int NumberOfControls = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["b1"] = 0;
}
else
{
if ((int)ViewState["b1"] > 0)
{
CreateBtn();
}
}
}
protected void btn1_Click(object sender, EventArgs e)
{
NumberOfControls = (int)ViewState["b1"];
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + ++NumberOfControls;
b1.Click +=new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
ViewState["b1"] = NumberOfControls;
}
protected void CreateBtn()
{
for (int i = 0; i < (int)ViewState["b1"];i++)
{
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + i;
b1.Click += new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
}
}
protected void btn11(object sender, System.EventArgs e)
{
Response.Redirect("AboutUs.aspx");
}

Resources