This code a have written for an asp.net website, v2005
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
phFname.Controls.Add(txtEFName);
placeHolder1.Controls.Add(TextBox1);
This code when executed, always shows the value of the textbox "" even if I enter some string.
Please help.
Dynamic controls need to be re-created each time the page loads. So you need to have that code execute during the Page_Init event. Note: You need to assign a unique ID for this control that stays the same each time the page loads.
Why all this?
Because the control is not contained in the markup (the .aspx file), you need to add it again every time the page loads. So how does it retain its value? The value will be stored in the ViewState, and as long as the control has the same ID it will be repopulated with the correct value.
To keep things running smoothly, let's put the code for adding the control in a separate function.
Private void AddMyControl()
{
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
txtEFName.ID = something unique;
phFname.Controls.Add(txtEFName);
}
So we can call it from both the click handler and the Page_Init handler, but we only need to call it in the Page_Init if we have already clicked. So let's store that as a flag inside a Session variable (you can also store it in the ViewState if you like, but let's keep it that way for now). So our click handler will now look something like this:
void ButtonSomething_Click(Object Sender, EventArgs e)
{
AddMyControl();
Session["MyControlFlag"] == true;
}
Now we need our Page_Init handler:
Public void Page_Init(Object Sender, EventArgs e)
{
if(Session["MyControlFlag"]!=null && (bool)Session["MyControlFlag"])
AddMyControl();
}
Related
May I know if there is any way to invoke a method from the child page(.aspx) after the page load of the user control is finished?
Right now I have an issue of being unable to retrieve the value from the child page because the variables from the user control has not been assigned the value yet.
To put it simply
FROM MY .ASPX FILE
Page_Load(object sender, EventArgs e)
{
x = getValueFromUserControl();
}
FROM MY USER CONTROL
Page_Load(object sender, EventArgs e)
{
int x = getvalueFromDatabase();
}
getValueFromuserControl()
{
return x;
}
Since the ASP.NET Life Cycle goes from the child page(.aspx) page_load -> user control page_load, I am unable to retrieve the value of x.
That said, ideally I would not like to put the function in the child page and call it from the user control as the user control is being used in other pages.
In short, I would like to invoke a method from my .aspx page after the page_load in my user control ends, Thank you!
Get the value at a later page event:
protected override void OnLoadComplete(EventArgs e) {
x = getValueFromUserControl();
}
Unless, of course, there is a specific reason why you must get the value on Page_Load. There are other, probably more appropriate ways to handle this, but without knowing what x is and what you need to do with it, it is hard to give any other advice. For example, maybe the UserControl should fire an event that is handled by the page.
I'm new with asp.net and i think this is really easy question, but i can't find the answer. I have a DropDownList on my page (that will be page A), one of the ways to go to that page is follow the link on the other page (page B). By this link i deliver some parameters, so i use them in the Page_load of page A:
protected void Page_Load(object sender, EventArgs e)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
But after it i couldn't choose something else exept this value, sometimes i saw that for a second new item is selected, but then in a blink of an eye it turns back to that preloaded one. I thought that .ClearSelection() will hepl, but it isn't (or maybe i use it in a wrong place). So i really wonder what to do and will really appreciate your help
One of the most important things you need to know about ASP.NET is the page life-cycle. There is plenty of help on the internet for this. Here is a quick link: http://blogs.msdn.com/b/aspnetue/archive/2010/01/14/asp-net-page-life-cycle-diagram.aspx.
Notice that the Page_Load event is fire before any event handling. This means that if you are using an event handler to catch changes in the dropdown your current code will reset it to the query string value first.
Of course that is a very big problem so ASP.NET has added a Page.IsPostBack property to help. This will be true only one the first load of the page and false for all event handling postbacks. Using this information you can tweak your routine to only apply the value when IsPostBack is false.
if (!Page.IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
Check if is it is a post back
if (!Page.IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
When you select a new item, does it invoke a post-back to the server? Possibly for a SelectedIndexChanged event?
If so, you're clobbering the selected value on each post-back. Page_Load gets invoked a lot. Any time the page does anything server-side, basically. It's part of the page lifecycle for everything the page does. So every event on the page (button click, selected index changed, etc.) is going to run the code in Page_Load before it runs any event handler code.
To avoid clobbering this value, you can wrap this code in a conditional to check if this is an initial page load vs. a triggered post-back:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
}
Inside a ListView Control's <ItemTemplate> I'm using a LinkButton.
When the List populates it has a set of LinkButtons. The link button text's are generated from a column in the records retrieved using a data source.
When I click on a LinkButton, I need it's text to be captured into either a hidden field or view state during the post back, so that it will be displayed in a Label or TextBox when page post back happens.
But it does not happen on first page post back. Instead, I have to click on the LinkButton twice for two post backs for the value to be displayed in Label/TextBox.
How can I get it done in the first post back ?
I have tried the same without the ListView, using just a LinkButton as below, and get the same outcome.
protected void LinkButton_Click(object sender, EventArgs e)
{
LinkButton selectedButton = (LinkButton)sender;
HiddenField1.Value = selectedButton.Text;
ViewState["LinkButtonText"] = selectedButton.Text;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(HiddenField1.Value))
{
Label1.Text = HiddenField1.Value;
}
TextBox1.Text = HiddenField1.Value;
if (ViewState["LinkButtonText"] != null)
{
if (!string.IsNullOrEmpty(ViewState["LinkButtonText"].ToString()))
{
ViewStateTextBox.Text = ViewState["LinkButtonText"].ToString();
}
}
}
Well, It happens since the sequence of the server side method execution. The page load before hand, then the control click methods, in that order. Instead of updating hidden field like that now using a client side JavaScript function OnClientClick of the LinkButton control, which updates the hidden field.
In short, you use it everytime you need to execute something ONLY on first load.
The classic usage of Page.IsPostBack is data binding / control initialization.
if(!Page.IsPostBack)
{
//Control Initialization
//Databinding
}
Things that are persisted on ViewState and ControlState don't need to be recreated on every postback so you check for this condition in order to avoid executing unnecessary code.
Another classic usage is getting and processing Querystring parameters. You don't need to do that on postback.
I am trying to develop a page.
that has a button and a placeholeder.
on the click of the button a user control is added to the placeholder.
on each click of button that many user controls should be added to the placeholder.
i am trying to store placeholder in viewstate on preinit event but while retrieving placeholder from viewstate in load event viewstate remains null.
below is my code:
protected void PreInit(object sender, EventArgs e)
{
this.OnPreInit(e);
if (!Page.IsPostBack)
{
ViewState["c"] = PlaceHolder1;
}
else { PlaceHolder1 = (PlaceHolder)ViewState["c"]; }
}
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{ PlaceHolder1= (PlaceHolder)ViewState["c"]; }
}
public void addDepartmentBtn_Click(object sender, EventArgs e)
{
// User Control Code
c1 = LoadControl("~/AddDepartment.ascx");
PlaceHolder1.Controls.Add(c1);
}
If viewstate is not suitable in this scenarion then what is the alternative way to achieve this ?
You have to re-add controls to your place holder on each post back.
Your attempt to ViewState is barking up the wrong tree-- ViewState is for something entirely different and even if you wanted to, you can only store serializable things into ViewState.
If you are trying to add controls to the page dynamically, that must be done in Init on each postback. This means that you must use a data structure (something persisted in ViewState will do) as a list of dynamically-created controls- NOT the controls themselves, but a hash of strings to use as IDs is a common method.
Each time the user does something to add a control to the page, add a key to the list. In the Page Init, you must then read the list and use it to recreate and add the dynamic controls back to the page collection or they will not appear on the page.
This is not going to work. ASP.NET server controls are too complex a thing to be stored in a ViewState. What server controls do, by ASP.NET design, is store their data (state, property values, etc) in Page's ViewState.
What you can do is store in ViewState the number of AddDepartment user controls that have been created and added to the placeholder. This can be done in PreRender. Then on postback, you read this number from the ViewState and create and add to placeholder that many AddDepartment controls.
Asp Textbox inside update panel displays value from database in page load. Button inside update panel triggers postback. Database procedure changes value to be displayed. Textbox text is updated from database in Page_Load, if (!Page.IsPostBack). It is confirmed that at the end of Page_Load the textbox has the updated value. Displayed value on screen does not change to updated value.
Based on other posts, I have tried moving the update of the textbox text to the OnPreRender event with the same result.
My only work-around so far is to re-create the control with a new ID on each postback so it will not be repopulated from posted data (using timestamp appended to ID) and finding the control by the base name using Regex. This way I can display the right value and read it on next postback, but it seems to be a cumbersome workaround.
What is the proper .NET way to update a textbox during postback and have the value "stick"?
If you use your texbox just for displaying purpose you shouldn't use if (!Page.IsPostBack)
If you need to use your textbox value. Then
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
TextBox1.Text = %YOUR_INITIAL_DB_VALUE%;
}
protected void Button1_Click(object sender, EventArgs e)
{
string userInput = TextBox1.Text;
TextBox1.Text = %YOUR_NEW_DB_VALUE%;
}