Why check box is checked after postback - asp.net

I have next code,
<form id="form1" runat="server">
<asp:Label runat="server" ID="Label1" EnableViewState="false" />
<asp:CheckBox runat="server" ID="Check1" EnableViewState="false" Checked="false" />
<asp:Button runat="server" ID="Button1" Text="Button1" />
</form>
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) return;
Label1.Text = "Label value";
Check1.Checked = true;
}
Why on postback text is despairing but check box still checked ?
Thanks

Citing references from this MSDN article - Understanding ASP.NET View State by Scott Mitchell doc:
Page Life cycle Stage 3 - Load Postback Data
It is a common misconception among developers that view state is
somehow responsible for having TextBoxes, CheckBoxes, DropDownLists,
and other Web controls remember their values across postback. This is
not the case, as the values are identified via posted back form field
values, and assigned in the LoadPostData() method for those controls
that implement IPostBackDataHandler.

Because the checkbox picks up the state from the form data, so that it remains checked when it is recreated.
The viewstate is only needed to remember what state the checkbox had before, so that the server side Change event works.

Related

Why do my dynamically added controls loose their values after Postback?

To ask my question I have created an aspx file containing a Button and a DataList with an SqlDataSource:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:DataList ID="DataList1" runat="server" DataKeyField="a"
DataSourceID="SqlDataSource1" >
<ItemTemplate>
a:
<asp:Label ID="aLabel" runat="server" Text='<%# Eval("a") %>' />
<br />
b:
<asp:Label ID="bLabel" runat="server" Text='<%# Eval("b") %>' />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:probaConnectionString %>"
SelectCommand="SELECT [a], [b] FROM [PROBA_TABLE]"></asp:SqlDataSource>
In my code behind I add TextBoxes to the Items of the DataList. I add to every Item a TextBox in the Page_Load, and another TextBox in the Button Click eventhandler as well.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (DataListItem item in DataList1.Items)
{
item.Controls.Add(new TextBox());
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
item.Controls.Add(new TextBox());
}
}
}
}
This works fine except one thing. When I click the Button, the TextBoxes which were created in the Page_Load keep their Text value, but the TextBoxes which were created in the Button1_Click lose their Text values. My real problem is more complicated than this, but I think solving this would help me a lot.
Each control that should receive data from page ViewState should be instantiated in Init or Load event handlers, because ViewState is persisted to controls BEFORE Click, Change and the rest control events (those events are triggered when ViewState changes are detected, so ViewState must be read before Click event is fired).
So the process should look like:
OnInit (static controls get created)
Static control content is deserialized from ViewState
OnLoad (create dynamic controls, in your case textboxes that you created in last Postback)
Dynamic control content is deserialized from ViewState
Click, Change and other events are fired according to changes detected comparing POST data and ViewState data
Suggestions:
You can use hidden fields to save additional status information, and then in OnLoad you can read that info to recreate dynamically created controls.
Also, you should explicitly set ID property of your textboxes so that values can be properly persisted back, don't rely on ASP.Net.
the http by default is stateless that means after your request is processed the server keeps no data or info of the request
but the values in the form need to be persisted in special cases when there is an error
suppose you fill up a long form and then post it back to the server only to get an error message and all the filled up values are gone. wouldn't that be annoying
so what asp.net does behind the scenes that it keeps a string in the page hidden that has information about all the server controls and their ids
so when you post a form back the Page class is created and the values that are posted back and binded in the specific controls because the Page class is being created in every request the pageLoad event is run and controls created in the PageLoad are then present values corresponding to their ids are put into them unlike the controls that are being created on button click till the button_click event is run that viewstate has already been deseralized and values are filled into them

asp.net set textbox control in panel contol

I want to set the textbox contol located in the panel control via code
I know to retrieve the inputted value in the textbox control:
string myVal = Request.Form["txtResult"];
I want to set the txtResult.text = "some text";
makeup snippet:
<asp:Panel ID="Panel1" runat="server" Style="display: none" Width="233px">
<asp:TextBox ID="txtResult" runat="server" AutoPostBack="True"></asp:TextBox>
<br />
<div align="center">
<asp:Button ID="OkButton" runat="server" Text="OK" />
<asp:Button ID="CancelButton" runat="server" Text="Cancel" />
</div>
</asp:Panel>
txtResult is not available within code, I tried to see if it is available in the page_load, it's not
texReults was a typo, its txtResult, I updated the ID
the intellisense does not recognize any cntr by the name txtResult
its a new web application and the panel visibility=True
maybee this wil help, above the snipet, I use ScriptManager from the AJAX Exstension
I am aware of he Asnchronius affects, partial potback, etc.
It's a managed control, you should be able to set it on the Page_Load event:
protected void Page_Load(object sender, System.EventArgs e)
{
txtResult.Text = "some text";
}
Update: Based on your update, there are a couple of things that you would need to check:
Spelling: Are you sure you're spelling the control name correctly?
Its ID in your code is "txtResults", but you're referencing it as
"txtResult".
Designer: Did you copy the aspx page or bypass VS in some way for this page? If so check the .designer file for the reference to the control: i.e. "Page1.aspx.designer.cs"
Visibility: Is the Panel control's visibility set to true? If not, then it won't render the controls that are contained within it.
Update 2: If you're doing this through scriptmanager, then I highly recommend that you read through this: http://www.wrox.com/WileyCDA/Section/Using-the-ASP-NET-AJAX-ScriptManager.id-305492.html

Telerik RadDock for ASP.NET AJAX initialization problem

I've run into a problem while using Telerik RadDock control for asp.net ajax. I'm generating the dock layout dynamically and there are multiple page configurations retrieved from the database. The thing is that I need to use post data before handling LoadDockLayout event, because there is a dropDownList which gives the ability to select one of avialable configurations.
I may be missing something, but it appears to me that LoadDockLayout event is fired before PreLoad event (it looks like the LoadDockLayout is fired before ProcessPostData method call) and before dropDownList selectedIndexChanged event, so I don't have the value I need to initialize dock layout properly.
I was thinking of converting my dropDownList to client side control and passing the selected value in query string, but it seems for me to be an ugly solution. Any advices would be appreciated.
Thanks in advance.
The RadDockLayout.LoadDockLayout event is fired at Page.InitComplete before any post data can be handled. If you want to load different controls based on a DropDownList selected item, you can do it by checking the parameters sent from the client. Here is an example on how you can retrieve them:
ASPX
<asp:Label ID="Label1" EnableViewState="false" runat="server" />
<asp:DropDownList ID="Dropdownlist1" runat="server" AutoPostBack="true">
<asp:ListItem Text="text1" Value="val1" />
<asp:ListItem Text="text2" Value="val2" />
<asp:ListItem Text="text3" Value="val3" />
<asp:ListItem Text="text4" Value="val4" />
</asp:DropDownList>
C#
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
var selValue = this.Request.Params.Get("Dropdownlist1");
Label1.Text = "EVENTTARGET: " + this.Request.Params.Get("__EVENTTARGET") + "<br/>Value sent: " + selValue;
}
}

AJAX TabContainer containing user controls

Wondering if someone here can help.
I have an AJAX tabcontainer which has a number of tabs and each tab contains a user control. When I add a new item from one of the tabs, it is not reflected in the user control in another tab unless a postback occurs. (e.g. the first tab has a listview where I add a new record and the second has a simple form which contains a drop-down which I expect to contain value added from first tab).
How can I make the tabcontainer to refresh its tabs from a usercontrol?
Any help will be most appreciated.
Thanks,
Ali
You could fire an event from your first user control so that the page can handle this event and tell the other usercontrol to databind
Here is a example
<act:TabContainer ID="TabContainer2" runat="server" CssClass="EmployeeProfile" ActiveTabIndex="0">
<act:TabPanel ID="TabPanel1" runat="server" HeaderText="Datos Generales">
<ContentTemplate>
<br />
<uc1:EmployeeGeneralDetails ID="EmployeeGeneralDetails2" runat="server" OnUpdated="EmployeeGeneralDetails2_OnUpdated" />
</ContentTemplate>
</act:TabPanel>
<act:TabPanel ID="TabPanel2" runat="server" HeaderText="Referenias Personales">
<ContentTemplate>
<uc3:EmployeeResumeView ID="EmployeeResumeView2" runat="server" />
</ContentTemplate>
</act:TabPanel>
</act:TabPanel>
protected void EmployeeGeneralDetails2_OnUpdated(object o, EventArgs e)
{
EmployeeResumeView2.DataBind();
}

Why aren't all controls initialised at the event handling point of the ASP.NET page lifecycle?

I have a user control embedded in a web part. It has the following snippets of code:
protected TextBox searchTextBox;
protected Button goButton;
protected Button nextButton;
protected Repeater pushpins;
protected Label currentPageLabel;
protected void goButton_Click(object sender, EventArgs e)
{
// Do stuff
}
<asp:TextBox ID="searchTextBox" runat="server" />
<asp:Button ID="goButton" runat="server" Text="Go" OnClick="goButton_Click" />
<asp:Repeater ID="pushpins" runat="server" EnableViewState="false">
<ItemTemplate>Blah</ItemTemplate>
</asp:Repeater>
<asp:Label ID="currentPageLabel" runat="server" />
<asp:Button ID="nextButton" runat="server" Text=" >> " OnClick="nextButton_Click" />
(There is no OnLoad or CreateChildControls method.)
If I place a breakpoint on the first line of goButton_Click, I find:
searchTextBox: initialised
goButton: initialised
nextButton: NULL
pushpins: initialised
currentPageLabel: NULL
Why are some controls initialised and others not? How do I get around this if I'd like to update the Text property on currentPageLabel?
Update:
I've placed breakpoints all the way through the page life cycle and found that nextButton and currentPageLabel are never initialised. The breakpoints were placed at OnLoad, CreateChildControls, goButton_Click, OnPreRender, Render and OnUnload.
Is it possible you've inadvertently got local variables named currentPageLabel and/or nextButton declared somewhere? The compiler will happily allow this...
This is especially common in a move from ASP.NET 1.1 to 2.0 or higher, since the way the designer defined these controls changed.
The problem was that all of the controls that weren't being initialised were inside a HeaderTemplate within a Repeater control. (To save space I didn't paste all of my code into the question, dang it.)
I moved them out and the problem is resolved. Obviously controls in the HeaderTemplate are instantiated by the Repeater and do not follow the normal page life cycle.

Resources