Retain textbox values on page refresh - asp.net

I have a textbox in a user control uc1. I have embedded this uc1 in a page called default.aspx. My issue is after running the application and entering some data in the textbox, when refresh the page i would like to show the values that i have entered in the textbox and not clear the textbox. I would like help with code on how to achive this. Thanks in advance for your help.

Create a global variable at the top of your aspx.cs page:
public string textboxValue
{
get
{
if (ViewState["textboxValue"] != null)
return ViewState["textboxValue"].toString();
else
return "";
}
set
{
ViewState["textboxValue"] = value;
}
}
Then, in PageLoad(), assign textboxValue a value:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
textboxValue = MyTextBox.Value;
else
MyTextBox.Value = textboxValue;
}
You can also use textboxValue to assign the value of MyTextBox at any time, or use it in any other way that might be useful to you.

The default behavior for all asp.net server side controls (runat="server") is to maintain their state. If your textbox is being cleared when your page refreshes, you are likely clearing that value yourself in code.
Are you dynamically adding the textbox or user control? If so, are you doing that during PageInit? Adding them later may cause them to lose state.

I was able to refresh the page without clearing the value in textbox. I did it as below:
I created a public property in the UC1.vb as below:
Public Property textbox_value() As String
Get
If Session("textbox1") IsNot Nothing Then
Return Session("textbox1").ToString()
Else
Return ""
End If
End Get
Set(value As String)
Session("textbox1") = value
End Set
End Property
And in the page_load event of the user control i added the code below:
If IsPostBack Then
textbox_value= textbox1.Text
ElseIf Not IsPostBack Then ' First time the page is loaded or when the page is refreshed
textbox1.Text = textbox_value
End If
Hope it helps.

Related

ASP.NET: TextBox.Text doesn't have updated value

I have an initialize function that loads data into my textbox NameTextBox, and then I add an "s" to the name. I then click the Save button that executes SaveButton_Click when debugging the value for NameTextBox.Text is still the original string (FirstName) and not (FirstNames). Why is this? Thanks.
Edit: Sorry here you go let me know if you need more...
Page_Load(sender, e)
Info = GetMyInfo()
Initialize()
Initialize()
NameTextBox.Text = Info.Name
SaveButton_Click(sender, e)
Dim command As SqlCommand
command = GetSQLCommand("StoredProcedure")
command.Parameters.AddWithValue("#Paramter", NameTextBox.Text)
ExecuteSQLCommand(command)
If the textbox is disabled it will not be persisted back to the codebehind, also if you set the initial value everytime (regardless of IsPostBack) you are essentially over writing what the value is when it gets to the Event handler (SaveButton_Click). Ex:
page_load() { NameTextBox.Text = "someValue";}
....
saveButton_Click() { string x = NameTextBox.Text;}
The above code will always have the text value of the textbox be "someValue". You would need to wrap it in an if(!IsPostBack) like so....
page_load() { if(!IsPostBack) {NameTextBox.Text = "someValue";}}
....
saveButton_Click() { string x = NameTextBox.Text;}

Is ctl00 a constant in ASP NET?

I need to reference a control in my web app that was generated with the use of a master page. The name of the control in the HTML becomes something like this "ctl00$MainContent$ListBox1". Can I safely do this in the code?
string strName = "ctl00$MainContent$ListBox1";
if (Request.Form[strName] != null)
{
String selectedLanguage = Request.Form[strName];
}
PS. I cannot use ClientID property because this code is called from InitializeCulture() override.
You could, but what I do is set the MasterPage ID in my Init():
protected void Page_Init( object sender, EventArgs e )
{
// this must be done in Page_Init or the controls
// will still use "ctl00_xxx", instead of "Mstr_xxx"
this.ID = "Mstr";
}
ctl00 is the generated ID of your masterpage. In the code-behind, you can set this.ID to whatever you want and any sub-content will be prefixed with that ID instead.
The problem with the code you have above is you're relying on a magic string for a control ID - you need to be careful with this as controls get moved into user controls and master pages become nested. I'm not sure why you can't use ListBox1.SelectedValue?

How to pass variable from page to another page in ASP.NET

I want to ask how to pass a variable from a page to another page.
example.
in (page1.aspx.cs) there is button click and textbox
protected void Button1_Click(object sender, EventArgs e)
{
textbox1.text = ;
}
in (page2.aspx.cs)
A = "hello"
// A is variable that can be change, A variable is coming from microC
What I want is show "hello" from page2 in textbox1.text when I click button1 in page1.aspx
You can pass the value as a querystring parameter.
So if you are using Response.Redirect you could do something like
protected void Button1_Click(object sender, EventArgs e){
Response.Redirect("Page2.aspx?value=" + taxtbox1.text);
}
On Page 2 you can get the value using Request["value"].ToString()
Notice that the querystring parameter name is what you request. So if you have ?something=else you will Request["something"]
One way is to place the value into some form of temporary storage: Cookie, Session, etc. And then redirect.
Another would be to redirect with a query string value. It really depends on your situation.
I'd recommend setting a session if this is necessary.
Session["sessionname"] = "";
Though it isn't ideal, is it possible to have everything on page1? You can switch with a panel control.
Without a Postback it is not possible!
With a Postback, yes it is (see Cross Page Postback). Also see in the link what you can have access to! (Access possibilities are page controls & public members).
Other options, Session variables, cookies, query string, etc!
u can use one of this ways:
1- Query string
page.aspx?ID=111&&Name=ahmed
2- Session
Session["session1"] = "your value";
3- Public property
public String prop1
{
get
{
return txt_Name.Text;
}
}
4- Controls Data
5- HttpPost

Using ASP.NET Cache/ViewState/Session

I'm trying to learn about Cache, Page ViewState, and Session. I created an ASP.NET web app in VS2010 and added 3 text boxes and a button to the page. I run in debug mode, enter random text into each, press the button, and nothing seems to be saved (all text is "null", as you'll see in the code). Am I performing these action in the wrong place? Do I need to add something to the web.config? Here is the code I'm using:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Cache["textbox1"] != null)
TextBox1.Text = (string)Cache["textbox1"];
else
TextBox1.Text = "null";
if (ViewState["textbox2"] != null)
TextBox2.Text = (string)ViewState["textbox2"];
else
TextBox2.Text = "null";
if (Session["textbox3"] != null)
TextBox3.Text = (string)Session["textbox3"];
else
TextBox3.Text = "null";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Cache["textbox1"] = "(Cache) " + TextBox1.Text;
ViewState["textbox2"] = "(VS) " + TextBox2.Text;
Session["textbox3"] = "(Session) " + TextBox3.Text;
}
And the page header:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="State._Default" EnableSessionState="True" EnableViewState="True" %>
Thanks, and sorry for the rookie question. I'm very new to this.
Page_Load happens before Button1_Click. So on Page_Load you always replace textbox text with something from statebags ("null" at first and then "(Cache)" + "null" etc). What you enter in textboxes never lives until Button1_Click.
Use Page_PreRender instead.
Right now, every time you click the button, the code in your Page_Load procedure is overwriting the TextBox.Text values before the Button1_Click event gets a chance to save them.
If you change if (IsPostBack) to if (!IsPostBack), the values will only attempt to be loaded from session/viewstate/cache when you initially request the page. So you would have to request the page, set new values with the button, then re-request (Enter key in address bar) to run the code in Page_Load.
What I would suggest is you create a new button called "Load Values" whose Click event will run the code currently found in your Page_Load. That way you don't have to tie that code to whether the request was a postback or not. I think it would make your test results much easier to understand.

How can I use a page_load local variable in event handler of a button

Im making a site in Visual Studio using vb and I have a variable in page_load but need its value in the event handler of a button for passing on session.
Any suggestions on how I can do this? Any help is appreciated
You can store a value in the CommandArgument property of a Button:
btn.CommandArgument = "Your value"
And then when handling the event you can pull it out:
CType(sender, Button).CommandArgument
You could also make a new class that extends Button and create new properties like below if you need multiple arguments:
Class SessionButton
Inherits Button
Public Property SessionGUID() As Guid
Get
Dim s As Guid = Nothing
If Not String.IsNullOrEmpty(ViewState("SessionGUID")) Then
s = New Guid(ViewState("SessionGUID").ToString())
End If
Return s
End Get
Set(ByVal value As Guid)
ViewState("SessionGUID") = value.ToString()
End Set
End Property
End Class
couldn't you just make the variable a class scoped variable, instead of local?
You can store it in a viewstate backed property:
Public Property MyStringVar() As String
Get
If ViewState("MyStringVar") = Nothing Then
Return String.Empty
End If
Return ViewState("MyStringVar").ToString()
End Get
Set
ViewState("MyStringVar") = value
End Set
End Property
Now using this property you can save your variable on page load and access it in the button click event handler.
EDIT: updated to VB
you declare the variable outside the page_load and then you can use it where you want :)
You could also create a class that encapsulates the action. Then you can capture any data you want and easily add to it later.
void Page_Load()
{
myBtn.Click += new MyButtonClass(variable).Run;
}
class MyButtonClass
{
int Param;
MyButtonClass(int param)
{
Param = param;
}
public void Run(object sender, EventArgs args)
{
// Do something usefull
}
}
If the data is created/retrieved on every Page_Load, this will work. If it is wrapped around an (! IsPostBack), the data must be stored in a session. Fortunatly, the class can be easily modified to store/load the variable from a session parameter.
I'm sorry for the c# code, maybe someone else can translate it then remove this message?

Resources