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%;
}
Related
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.
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();
}
I turned off AutoPostback on my control because I need to validate something with javascript. And if everything is ok I'm doing postback clikcing on hidden button. The problem is that combobox looses selected value on page reloading.ViewStateMode set to Enabled. I'm populating combobox in page_load event:
protected void Page_Load(object sender, EventArgs e)
{
(!IsPostback)
{
InitializeItems(); // Helper method that binds data
}
}
Before going into the internals of Telerik, you can try to resolve the original problem. You said you want to perform validation before the postback takes place.
All you have to do is register the script you want to be ran on form submit:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.Page.ClientScript.RegisterOnSubmitStatement(typeof(YourClass), this.UniqueID, "your validation script here.");
}
Then in order to cancel the postback, your validation script needs to return false.
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.
I have a GridView to which I've using an ObjectDataSoure as the data source. The ObjectDataSource is taking in parameters from a TextBox and DropDownList which is then passed into the stored procedure. There is also a button called Search which can be used to force a refresh on the GridView by providing/changing values in the TextBox and/or DropDownList. However I noticed that if I changed the values I don't have to click on the Search button; simply clicking on the GridView causes a data bind.
Is there anyway to prevent this action while still using the ObjectDataSource?
When you assign a DataSourceID on the GridView, the grid will automatically bind to the ObjectDataSource. You can simply omit that property on the GridView and wait until the Search button's click event to assign it.
The problem is that every time any parameter used for ObjectDataSource is changed the ODS performs a "DataBind".
You can use two HiddenFields to keep the values. The ObjectDataSource will only do a "DataBind" when you change the values on the HiddenFields. So you can change the values on the TextBox and DropDownList, and when you want a "DataBind" you only need to copy the values to the HiddenFields.
Here is a code sample I made for another question: Q11874496WebApp.7z
In my case i just used a private boolean field in codebehind and respect its values on datasourceName_Selecting event.
For example i declared the following:
private bool IsInSearchingMode = false;
set it true only in search mode:
protected void btnSearch_Click(object sender, EventArgs e)
{
this.IsInSearchingMode = true;
this.gridData.DataBind();
}
and then check the value on Selecting event:
protected void myLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
e.Result = new List<BranchDataClass>();
if (!this.IsInSearchingMode)
return;
// e.result = select code
}
A drawback is that a new page_load that is not caused by btnSearch_Click will reset the private variable's value. If you want it to be persistent you should use a hidden field as proposed or save it to viewstate.