runat server field not filled when clicking on button? - asp.net

I'm using an aspx file as my main page with the following code snippet:
<input type="text" runat="server" id="Password" />
<asp:Button runat="server" id="SavePassword"
Text="Save" OnClick="SavePassword_Click"/>
Then in the code behind I use:
protected void SavePassword_Click(object sender, EventArgs e)
{
string a = Password.Value.ToString();
}
Setting Password.Value in the Page_Load works as expected, but setting a to the value results in an empty string in a regardless what I type in on the page befoere I click the save button.
Am I overlooking here something?

You should add label field with name labelShow in aspx page like this
<asp:Label ID="labelShow" runat="server"></asp:Label>
Then add the string into .cs file
protected void SavePassword_Click(object sender, EventArgs e)
{
string a = Password.Value.ToString();
labelShow.Text = a.ToString();
}

I can figure several errors :
You say something about Page_Load. You should always remember Page_Load is executed at every postback. So if you write something into the textbox at Page_Load, it will erase the value typed by user. You can change this behavior by veriyfing
if(!IsPostBack)
{
// Your code
}
around your Page_Load content.
input runat="server" is not the proper way to do TextBox in ASP.Net, in most cases you should use asp:TextBox
You don't do anything with your "a" string, your current code sample does nothing, whether the Password field is properly posted or not. You can do as suggested by Ravi in his answer to display it.
I suggest you to to learn how to use VS debugger, and to read a good course on ASP.Net Webforms to learn it.

Related

ASP.Net AjaxControlToolkit CalendarExtender not updating Textbox in code behind

Have the following:
<asp:TextBox ID="txtStart" runat="server" Enabled="false"></asp:TextBox>
<asp:Image ID="ibDateS" runat="server" ImageUrl="../SystemImages/calendar.gif" ToolTip="Click to show calendar" AlternateText="Click to show calendar" CssClass="showpointer" />
<ajaxToolkit:CalendarExtender ID="ceStart" PopupButtonID="ibDateS" Format="dd/MM/yyyy" TargetControlID="txtStart" runat="server"></ajaxToolkit:CalendarExtender>
It all works ok on the DOM and the textbox gets updated with the new date BUT when I try to get the value in code behind i.e. txtStart.Text it still has the original value set on Page_Load.
Have I missed something?
EDIT:
TextBox set originally in Page_Load (yes contained in if(!IsPostback)):
txtStart.Text = DateTime.Now.ToString("dd/MM/yyyy");
Get it later like so:
DateTime dtStart = Convert.ToDateTime(txtStart.Text);
After a bit of research apparently its an issue with setting the textbox to readonly or enabled="false" on the page. Removing this and adding the following to page_load solved the problem:
txtStart.Attributes.Add("readonly", "readonly");
if you haven't use Page.IsPostBack property of page then plz use it and try to use you pageload code inside that. It seems that it may be the problem of Page.IsPostBack,Try for that
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Your code for databind...
}
}
Hope you understand and works for you..
Enabled false preventing it to post the latest value.

Controls within .ascx are not displaying their new value on postback

This seems like an elementary issue but it has me stumped.
I have a main page which loads a custom control (.ascx) on page_load.
This custom control has two fields. One of them being a dropdownlist and the other being a text box. When the dropdownlist changes value it triggers a post back, some logic is executed server side and a value is generated for the textbox. I stepped through the code and the value is created and assigned correctly. However, when the page is rendered the value does not change.
If I change the textbox value to "QQQ" and trigger the postback, "QQQ" stays in the textbox so I can verify viewstate is working.
Is there any reason why the generated value is not being displayed in the form on postback. This process works fine on the initial page load.
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string ascxPath = #"~/_CONTROLTEMPLATES/TRC_BITS.ascx";
TRC_BITS control = Page.LoadControl(ascxPath) as TRC_BITS;
phForm.Controls.Add(control);
}
.ascx
<asp:TextBox ID="message" runat="server" TextMode="MultiLine" /><br/>
<asp:DropDownList ID="year" runat="server" AutoPostBack="true">
<asp:ListItem Text="2011">2011</asp:ListItem>
<asp:ListItem Text="2012">2012</asp:ListItem>
<asp:ListItem Text="2013">2013</asp:ListItem>
</asp:DropDownList>
.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
year.SelectedValue = DateTime.Now.Year.ToString();
}
if (year.SelectedValue == 2012)
message.Text = "ABC";
else
message.Text = "XYZ";
}
Because you're adding these controls to the page dynamically, you need to assign an ID to the user control. Make sure to assign the same ID to the controls every time the page is posted back, and the fields will be repopulated from ViewState.
Also, as Shai suggested, it would be more appropriate if you loaded the controls during OnInit instead of Page_Load. The situation is a little different with user controls, but in general you want to add your dynamic content before the LoadViewState method is executed.
If you're looking for something to take the pain out of persisting dynamic content, I would suggest taking a look at the DynamicControlsPlaceHolder.
Because you are adding the controls dynamically, you need to add them during the page's oninit event.
Try it, believe me. Go for it. Yalla.

hidden field is null on !IsPostBack and not null on IsPostBack

First I'll apologize for the unclear title of my question. I wasn't sure how to succinctly describe my problem in a title.
I have a hidden field in my .aspx
<input type="hidden" name="hid1" value="0" />
I want to set the value of this field during the page load event, and if it is not a postback.
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
// This doesn't work!
Request.Form["hid1"] = "1";
}
if (Page.IsPostBack) {
// This DOES work!
Request.Form["hid1"] = "1";
}
}
The problem is that the Request doesn't contain the hidden field in the Form array during the page load event when it's not a postback (ie - the first time the page is hit). Subsequent hits to the page (ie - postbacks) result in the Form array containing the hidden field.
I'm sure that it has to do with the lifecycle of the page, but what I really need to know is how do I set the hidden field during the page load event and when it is not a postback?
EDIT:
I really, really don't want to incorporate the runat="server" attribute!
You could define a property in your page class and then modify the property value in your code:
protected string HiddenFieldValue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
HiddenFieldValue = "postback";
else
HiddenFieldValue = "not postback";
}
Then define the hidden form field like this so that it's value is set to the property value:
<input type='hidden' id='hidden1' value='<%=HiddenFieldValue %>' />
If you only want to set the value form the property during a postback or non-postback you could add the condition as well:
<input type='hidden' id='hidden1' value='<% if(IsPostBack) { %> <%=HiddenFieldValue%> <% } %>' />
Try converting the input into a HiddenField control (or, at least, a runat="server" input), and reference it by it's ID, rather than through Request.Form.
Instead of:
<input type="hidden" name="hid1" value="0" />
try this:
<asp:HiddenField runat="server" ID="hid1" />
Then in your Page_Load()
hid1.Value = "whatever...";
It will be visible both before and after postback when you declare it in this manner.
Why don't you make it a server control by setting 'runat="server"' on the input control? Then it will be accessible from your code behind, and you will be able to set the value during the first page load.
why dont you access that field through a style class and use runat server=?

ASP.Net repeater Item Command not getting fired

OK, I've used repeaters literally hundreds of times without problems but something has gone awry today. I have a repeater and I'm subscribing to the itemCommand event, but when my command runs, the page posts back but the event isn't fired.
To get around this I'm having to do my databinding on each postback.
My repeater looks like this:
<asp:Repeater id="MyRepeater" runat="server" onitemcommand="MyRepeater_ItemCommand">
<ItemTemplate>
<li>
<asp:Label id="Label" runat="server" />
<asp:LinkButton id="LinkButton1" runat="server" commandname="Complete" commandargument='<%# Eval("MyID") %>' text='<%# Eval("Title") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
and my codebehind like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetupPage();
}
}
private void SetupPage()
{
// Do other stuff
MyRepeater.DataSource = Repository.GetStuff()
MyRepeater.DataBind();
}
protected void MyRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
// Do all my stuff here
}
MyRepeater_ItemCommand is not getting called unless I comment out the if (!IsPostBack) line. Once that is commented out and the repeater is getting databound on each postback it works OK. I've done this in so many other pages but on this on it just doesn't seem to work.
Anyone else come across this behaviour or have a solution?
Most likely, you have disabled ViewState for the page.
The reason is that when you execute the postback, all the controls in the repeater are rebuild from the data in the viewstate normally. Then the object that should receive the event is identified based on the ID of the control, and the event is routed.
If you disable the viewstate, the control tree is not rebuild during postback, and therefore the control that should receive the event does not exist in memory. So the event dies.
If you really want to disable the viewstate, but still want to receive the event, I have a workaround (and it's not dirty at all). I've long been thinking about writing a blog entry about it, so if you want, I can take a bit time off my normal chores, and describe it.
Edit: The workaround is described here: http://petesdotnet.blogspot.dk/2009/08/asp.html
Remove if (!IsPostBack) as this is preventing the repeater from rebinding,
and the item command event could not find the row after postback.
I have the same problem and aside from using update panel, I have a required field validator in my modal. I found out that the LinkButtons in my repeater triggers the requiredFieldValidor event and then I added CausesValidation="false" in the LinkButtons of my repeater. Works as expected.
I have this problem in a repeater when I use ImageButton ...
I have search the net for this solution when LinkButton work, but not ImageButton ...
Then I think, LinkButton work? so i will use it :)
<asp:LinkButton CommandName="Filter" CommandArgument='<%# Eval("ID") %>' Text="" runat="server" >
<asp:image imageurl='<%#Eval("Img") %>' runat="server"/>
</asp:LinkButton>
So, the image is inside the <A> tag
have fun :)
I removed PostBackUrl property in linkbutton and ItemCommand fired. I think postback runs first.
That may be you have set Validations on your page. So set an new attribute, causevaliation = "false" to Link button. M sure it will solve the problem
I had a similar issue - turned out some discreet validation controls were firing elsewhere on the page. It only took me a day to figure it out ...
I am not positive about this, but you might have to set the CommandName and optionally CommandArgument properties for the button causing the ItemCommand event. Otherwise ASP.NET would assume that there is no button on the page, which you'd like to fire the event. You can try that.
Plus, if you're not differentiating between command names, why not use each button's Click event instead? Just subscribe to those in the repeater's ItemCreated or ItemDataBound.
Try using Page_init instead of Page_load and that should fix the problem.
Try this:
protected void Page_Load(object sender, EventArgs e)
{
SetupPage();
}
If you use nested-repeater, you should rebind your inner repe
Here Is the code you have to use in code behind..
after PageLoad event,
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Bind Your Repeater here
rptUser();
}
now you can fire your Itemcommand..if you get Output please mark answer as right thanks
One other thing that it could be (as it just happened to me): if your databind takes place when your page is prerendered, it won't process the item command. Switch it to load or init and you'll be fine.

ASP.NET AJAX Toolkit - CalendarExtender is reset on Postback

I have an ASP.NET page that has two input elements:
A TextBox that is ReadOnly. This TextBox is the TargetControl of a CalendarExtender
A DropDownList with AutoPostBack=true
Here is the code:
<table border="0" cellpadding="0" cellspacing="0">
<tr><td colspan="2">Date:</td></tr>
<tr><td colspan="2">
<asp:TextBox ID="dateTextBox" runat="server" ReadOnly="true" />
<ajax:CalendarExtender ID="datePicker" runat="server" Format="MM/dd/yyyy" OnLoad="datePicker_Load" TargetControlID="dateTextBox" />
</td></tr>
<tr><td colspan="2">Select an Option:</td></tr>
<tr>
<td>Name: </td>
<td><asp:DropDownList ID="optionsDropDownList" runat="server" AutoPostBack="true"
OnLoad="optionsDropDownList_Load"
OnSelectedIndexChanged="optionsDropDownList_SelectedIndexChanged"
DataTextField="Name" DataValueField="ID" />
</td></tr>
<tr><td><asp:Button ID="saveButton" runat="server" Text="Save" OnClick="saveButton_Click" /></td></tr>
</table>
When the DropDownList posts back, the date selected by the user with the datePicker is reset to the current date. In addition, if I look at the Text property of dateTextBox, it is equal to string.Empty.
How do I preserve the date that the user selected on a PostBack?
Certainly you must do as others have already suggested: set readonly field dynamically rather than in markup, and make sure you are not accidentally resetting the value in Page_Load() during postbacks...
...but you must also do the following inside Page_Load(), because the CalendarExtender object has an internal copy of the date that must be forcibly changed:
if (IsPostBack) // do this ONLY during postbacks
{
if (Request[txtDate.UniqueID] != null)
{
if (Request[txtDate.UniqueID].Length > 0)
{
txtDate.Text = Request[txtDate.UniqueID];
txtDateExtender.SelectedDate = DateTime.Parse(Request[txtDate.UniqueID]);
}
}
}
The fact that the text box is read only appears to be causing this problem. I duplicated your problem using no code in any of the bound events, and the date still disappeared. However, when I changed the text box to ReadOnly=False, it worked fine. Do you need to have the textbox be read only, or can you disable it or validate the date being entered?
EDIT: OK, I have an answer for you. According to this forum question, read only controls are not posted back to the server. So, when you do a postback you will lose the value in a read only control. You will need to not make the control read only.
protected void Page_Load(object sender, EventArgs e)
{
txt_sdate.Text = Request[txt_sdate.UniqueID];
}
If you want the textbox contents remembered after the postback and still keep it as readonly control, then you have to remove the readonly attribute from the markup, and add this in the codebehind pageload:
protected void Page_Load(object sender, EventArgs e){
TextBox1.Attributes.Add("readonly", "readonly");
// ...
}
The solution to the issue is making use of Request.Form collections. As this collection has values of all fields that are posted back to the server and also it has the values that are set using client side scripts like JavaScript.
Thus we need to do a small change in the way we are fetching the value server side.
C#
protected void Submit(object sender, EventArgs e)
{
string date = Request.Form[txtDate.UniqueID];
}
I suspect your datePicker_Load is setting something and not checking if it's in a postback. That would make it happen every time and look like it was 'resetting'.
In stead of setting ReadOnly="False", set Enabled="False". This should fix your issue.
#taeda's answer worked for me. FYI, if someone uses enabled = "false" instead of readonly = "true" wont be able to use that answer, because Request[TxtDate.UniqueId] will throw a null exception.
It is not a problem of Preserving,after setting readonly = true the value of the particular textbox doesn't be returned back to server
so
Use contentEditable="false" and made readonly = false
that would prevent value is being entered other than Calendar Extender selection also returns the value of the Text box back to the server

Resources