How to I carried out Textbox value from ViewState when I postback? - c#

I want to know that how can I trace out the value of Textbox from ViewState.
As user enters any value into Textbox and click submit button because of postback Textbox value disappears ,
But if I used ViewState in this case , then is there any way to see or display that value from Viewstate?
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /
</form>
</body>
</html>
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text += "X";
}

In your page load use this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (ViewState["Values"] == null)
{
ViewState["Values"] = new string();
}
}
TextBox1.Text = ViewState["Values"].ToString();
}
After that use this.
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Values"] += TextBox1.Text;
}
In the first Page_Load method, You will create a ViewState if its not a postback and its null. After that write the textbox your viewstate, in Button1_Click you will add your new textbox1 to your viewstate.

Related

Checking if the value of a textbox is changed or not

I have a textbox filled at the page load. I want to check the value of the textbox is changed or not in the "update" button press. Any solution? TIA.
Well, you could say use client side javascript.
But, you could also do this:
Say this text box:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Done - continue" OnClick="Button1_Click" />
And our code could be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// code here to setup and load controls
TextBox1.Text = "Dog";
ViewState["TextBox1"] = "Dog";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != (string)ViewState["TextBox1"])
{
// then text box was changed
}
}

persist ddl values and selected value in between postbacks

I have a save button and a drop down list on a page. Inside the page Load, the drop down list is populated if !Page.PostBack (AutoPostBack=false). So, the first time I load the page, the drop down list is populated. I also have a save method to go with the save button. When this button is clicked, it should do something with the selected value of the drop down list. My problem is that the drop down list has no value (is null) inside the button save method. How would you fix this?
Markup:
MyClass.aspx
<%# Page Language="C#" AutoEventWireup="true" Inherits="MyClass" %>
<asp:Content ID="Content3" ContentPlaceHolderID="MainRegion" runat="server">
<div>
<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="myDdlChange" ViewStateMode="Enabled" EnableViewState="true" />
</div>
<br />
<div style="min-width: 300px; max-width: 770px;">
<asp:TextBox id="txtBox" runat="server" TextMode="MultiLine" />
</div>
<div class="buttonContainer">
<span >
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
</span>
</div>
</asp:Content>
Then, in the code behind:
MyClass.aspx.cs
public class MyClass
{
protected global::System.Web.UI.WebControls.DropDownList myDdl;
protected global::System.Web.UI.WebControls.TextBox txtBox;
protected global::System.Web.UI.WebControls.Button btnSave;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (this.Page.IsPostBack)
Session["selectedID"] = myDdl.SelectedValue; // my attempt to put the selected value from ddl in a session var, to use it later inside the save method but it didn't work
if (!Page.IsPostBack)
{
//create array1 here
myDdl.Items.Clear();
myDdl.Items.AddRange(array1);
Session["selectedID"] = myDdl.SelectedValue;
myDdlChange(null, null);
this.DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
//do something based on myDdl.SelectedValue (which shouldn't be null)
}
protected void myDdlChange(object source, EventArgs e)
{
txtBox.Text = myDdl.SelectedValue;
}
}
}
I think the main problem is you should be using Page_Load instead of OnLoad.
You don't need to use Session to remember the SelectedValue.
Try something like this which works for me...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateDropdown();
}
private void PopulateDropdown()
{
myDdl.Items.Clear();
var array1 = new ListItem[3];
array1[0] = new ListItem("item1", "item1");
array1[1] = new ListItem("item2", "item2");
array1[2] = new ListItem("item3", "item3");
myDdl.Items.AddRange(array1);
myDdl.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
var selectedVal = myDdl.SelectedValue; // putting a breakpoint here shows myDdl.SelectedValue is not null
}
protected void myDdlChange(object sender, EventArgs e)
{
}

Inject a textbox in WebForms and retain the value on postback

I have a WebForms page that I would like to inject some additional controls into at runtime. Currently I am achieving this in the Page_Load event using a Literal control.
For example the page looks like this (note that the TextBox1 is not an asp control just to show that it works):
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<input id="TextBox1" type="text" runat="server"/>
<asp:Literal ID="Literal1" runat="server" Visible="false"></asp:Literal>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Content>
And the code behind:
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Visible = true;
if (!IsPostBack) Literal1.Text = "<input id=\"TextBox2\" type=\"text\" runat=\"server\"/>";
}
This works fine and both textboxes appear on the screen but if I type a value in to both and trigger a postback only the value of TextBox1 is retained.
I have tried moving my code to OnPreRender and OnPreLoad but still have the same issue.
I have noticed that when I view the page source TextBox1 has a UniqueId (e.g. ctl00$MainContent$TextBox1) while Textbox2 still has runat="server" as an attribute.
You can't inject server controls like this. You would need to add them as suggested in #Arvin's answer.
However, you use inject non-ASP.NET HTML controls similar to what you are doing and get their values.
From your code change the input's id to a name and drop the runat="server":
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Visible = true;
if (!IsPostBack) Literal1.Text = "<input name=\"TextBox2\" type=\"text\" />";
}
Then you can get it's value on postback:
string textbox2value = Request.Form["TextBox2"];
Then, if you want to add the control on postback with it's value:
Literal1.Text = "<input name=\"TextBox2\" type=\"text\" value=\"" +
Server.HTMLEncode(textbox2value) + "\" />";
if you want to inject a textbox you should use placeholder like this :
<input id="TextBox1" type="text" runat="server"/>
<asp:PlaceHolder ID="plh" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
protected void Page_Load(object sender, EventArgs e)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox2";
plh.Controls.Add(TextBox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var Text1 = TextBox1.Value;
var Text2 = Request.Form["TextBox2"];
}

Timer, UpdatePanel and dynamically created buttons

I have an update panel with a div (with runat="server") so I dynamically create and add buttons to it on a timer tick event.
The problem is that when a button is click, the is a postback but the button is gone and the event is not raised.
Here's my aspx page and my c# code behind. Nothing I write in the btn1_click actually occurs.
There's a continue to my question but in order to keep it simple, I would like to understand the above first.
I really need your help and i appreciate it, ty.
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="2000" ontick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<div id="div1" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="div2" runat="server">div2</div>
</form>
</body>
and this c# here.
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Timer1_Tick(object sender, EventArgs e)
{
CreateControl();
}
void CreateControl()
{
Button btn1 = new Button();
btn1.ID = "btn1";
btn1.Text = "click me";
btn1.Click += new EventHandler(btn1_Click);
div1.Controls.Add(btn1);
}
void btn1_Click(object sender, EventArgs e)
{
div1.InnerHtml += "btn1 was clicked";
}
}
For dynamically added controls you must add them in every page load event. Otherwise by the time it gets to the click event the are already gone. In this case I would add the button to a session collection of buttons every time you create one, then reload that entire collection on every postback, so it doesn't lose what you've already added. Also, save an int in session that you increment so they dont all have the same ID. IDs should be unique
something like:
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
CreateControls(YourCollectionInSession)
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
CreateControl();
}
void CreateControl()
{
Button btn1 = new Button();
btn1.ID = "btn" + yourSessionID;
btn1.Text = "click me";
btn1.Click += new EventHandler(btn1_Click);
div1.Controls.Add(btn1);
yourSessionID++;
YourCollectionInSession.Add(btn1);
}
void CreateControl(List<Button> buttons)
{
foreach(Button btn in buttons)
{
div1.Controls.Add(btn);
}
}
I've had to do the same thing before and this approach worked for me. Just remember the ASPx Page Lifecycle. It will always hit the page_init and page_load before it handles any post back events, meaning your controls are long gone.

Input text box value is not changing

In my .aspx page I have a 'input' html tag, also an asp button.
<input id="Name" type="text" runat="server" clientidmode="Static" />
<asp:Button Width="100" type="submit" ID="sendOrder" runat="server" OnClick="SubmitForm" Text="Submit" />
On page load, I am filling the value in input tag from code behind, like this:
Name.Value= "X";
But now if I change value of this text box from browser, lets say "Y", and click on Submit button, then I get the old value, but not the new one.
protected void SubmitForm(object sender, EventArgs e)
{
var test= Name.Value; // here I get old value
}
How can I get the altered value?
Make sure you are only setting the value to "X" when its not a postback:
if (!Page.IsPostBack){
Name.Value= "X";
}
Otherwise when clicking the submit button, the Page_Load() event will change the value from "Y" back to "X".
You need to use !IsPostBack on Page_Load shown as below:
protected void Page_Load(object sender, EventArgs e)
{
//it's important to use this, otherwise textbox old value overrides again
if (!IsPostBack)
{
Name.Value= "X";
}
}
Suggestion:
We can use use <input></input> control in asp.net but best practice is to use <asp:TextBox></asp:TextBox> control instead.
Here is the sample example:
HTML
<asp:TextBox ID="Name" runat="server"></asp:TextBox>
<asp:Button Width="100" ID="sendOrder" runat="server" OnClick="SubmitForm"
Text="Submit" />
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
//it's important to use this, otherwise textbox old value overrides again
if (!IsPostBack)
{
Name.Text = "Some Value";
}
}
protected void SubmitForm(object sender, EventArgs e)
{
var test = Name.Text; //now get new value here..
}
Check for IsPostback in Page_Load so you don't overwrite the values that are submitted!
You don't need all the else portion, just do this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//code to execute here only when an action is taken by the user
//and not affected by PostBack
}
//these codes should be affected by PostBack
}

Categories