I have a text box like this:
<asp:TextBox runat="server" ID="reasonNameTextBox"></asp:TextBox>
when I load the page in the first time, i put a value inside it like this:
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
Then, the user can enter his new value, and click save button.
My problem
when the user clicks save button, the value of the text box is still the value that I assigned when the page is loaded, not the value the the user has written.
I tried to use Google Chrome F12 feature, and I found the error.
Please look at this image
as you see, the value that i wrote in the text box is New Value, however, the value in the text box (when using F12) is still s, where s is the value that I assigned when the page is loaded.
why is that please?
The is because every time you are clicking on the button you are posting back and the page is again reloaded, Thus calling Page_Load, Which in turn is assigning the value you have assigned during page load.
To avoid this you need to do something like this :-
If(!IsPostback)
{
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
This, wouldn't update your textbox value with defaultvalue you have set during Page_Load and will take user updated value.
Changing the value doesn't update the DOM (unless you change it via javascript). So inspecting the textbox via developer tools, as you did, yields the text value you received from your server.
The interesting part lies in your WebPage's CodeBehind file. I assume it looks similar to this:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var results = GetResults();
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
}
In this case the textbox's value will be set every time, regardless of the user-input. What you have to do, is look for a postback:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var results = GetResults();
if (IsPostBack)
{
// retrieve the user input
var input = reasonNameTextBox.Text;
}
else
{
// set default value
reasonNameTextBox.Text = results.Rows[0]["reasonName"].ToString();
}
}
}
Related
I'm trying to pass a value from a User Control to a code behind without luck. I can write the correct value (IDuser_uc) on the aspx page but I can't pass it to the code behind. Any tips?
User Control
protected void FormView_IDuser_DataBound(object sender, EventArgs e)
{
Label IDuserText = FormView_IDuser.FindControl("IDuserLabel") as Label;
IDuser_uc = Convert.ToString(IDuserText.Text);
}
ASPX page
<uc4:IDuser id="IDuser" runat="server" />
<% Response.Write(IDuser.IDuser_uc); // Here correct value %>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource_userConnections.SelectParameters["IDuser_par"].DefaultValue = IDuser.IDuser_uc ; // Here NO value
Response.Write("Connections :" + IDuser.IDuser_uc); // Here NO value
}
UPDATE
The problem was due to the fact that the User Control is run after the PageLoad which explains why I got an empty string. To solve the problem I used Page_PreRender instead of Page_Load on the code behind page.
Create a public method in your user control. When you post back the page have the Parent.aspx page call the user control method. Example....
In your User Control:
Public string GetUserControlValue()
{
return Label IDuserText;
}
In your Parent ASPX Pgae
var UserControlString = IDuser_uc.GetUserControlValue();
I'm having a hard time figuring this out and I hope you guys would help me.
I have a page called Index.aspx with a DropDownList that is a separate UserControl class (because it will be used in other pages). Here's the code for that:
UcSelecionarLocal.ascx:
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="UcSelecionarLocal.ascx.cs"
Inherits="QuickMassage.uc.UcSelecionarLocal" %>
<asp:DropDownList ID="ddlLocais" runat="server"
CssClass="span4 dropdown-toggle" AutoPostBack="true">
</asp:DropDownList>
UcSelecionarLocal.ascx.cs:
public partial class UcSelecionarLocal : UserControl {
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack) {
PreencherLocais();
}
}
private void PreencherLocais() {
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows) {
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(),
row["ID"].ToString()));
}
}
}
This control is placed in Index.aspx and loads its values correctly. The form that it's contained in, has the action set to agendamentos.aspx. When I change the ddlist, the page is submitted to the forms action page, as it should be.
On the other page the problems begin: I get the parameters posted to this page and one of them is the ddlist value. In the immediate window, I check the value and it's there, let's say that it is 1.
To make long story short, I have this code:
agendamentos.aspx.cs:
protected void Page_Load(object sender, EventArgs e) {
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
While debugging, I see that locais.SelectedIndex is -1. After the assignment it remains -1. The page loads and then I change the ddlist value again to 2. When debugging the same code above, I see that the locais.SelectedIndex is now 1. Again, setting it to 2, as it would normally be, produces no effect. If I change the ddlist again to 3, the SelectedIndex becomes 2 and does not take the value 3.
In other words: the value of the index in a newly loaded page is the value of the page that was loaded before.
Could you guys help me?
This is because the Page_Load event is firing in your page before the user control is loading. Do this:
public partial class UcSelecionarLocal : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void PreencherLocais()
{
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows)
{
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(), row["ID"].ToString()));
}
}
}
Then in your aspx page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.idOfYourUserControl.PreencherLocais();
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
}
Also because your question is a little confusing, an important note is that Page_Load fires before data is captured from controls that post back data. So that's a bad place to get their information because it will be what it was previously. That's why you need to create a function that fires on something like a button click that will execute after the controls data have been loaded.
I have a textbox and a button. On page load I select one column from one row and put its value in the textbox. I have a button click method that updates the same column/row with the value in the textbox.
The problem i'm having is that when I clear the text in the text box, type in new data and hit submit the new text value is not being saved, it uses the old one.
I put a breakpoint at the end of my button click method and it appears that asp.net is sending the old value of the textbox rather than the new one I put in. I'm totally stumped.
This problem persists even if I have viewstate false on the textbox.
Both of my LINQ queries are wrapped in a using statement.
Any Ideas?
Edit: Here is the full code:
protected void Page_Load(object sender, EventArgs e)
{
using (StoreDataContext da = new StoreDataContext())
{
var detail = from a in da.Brands
where a.BrandID == 5
select new
{
brand = a,
};
foreach (var d in detail)
{
txtEditDescription.Text = d.brand.Description;
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (StoreDataContext dk = new StoreDataContext())
{
Brand n = dk.Brands.Single(p => p.BrandID == 5);
n.Description = txtEditDescription.Text;
dk.SubmitChanges();
}
}
As you said, in Page_Load you are retrieving the original value into the text box which overwrites any changes.
Yes, Page_Load DOES execute before Button Click (or any other control events) is executed. I'm going to guess you have done Windows Forms development before this, the ASP.Net web forms event model is quite different. Check out the ASP.NET Page Life Cycle Overview.
I figured it out. I should be be using if(!IsPostBack) on the code that originally fills the textbox with its value.
However this makes no sense to me. If the page is loaded and the textbox text gets a value, then you clear this value and try to insert it into the database, it should insert this value and then when the page post back it will fetch the new value from the database and put the value in the textbox.
The way it's actually working makes it seem like it is executing the page load code before the button click code is executed on post back.
just to trace the error,please try to put a label =( lblDescription.Text ) and leave the rest of code as is,put the new value in the textbox (editdescription.text) try it and tell me what you see
foreach (var d in detail)
{
lblDescription.Text = d.brand.Description;
}
I have a start page with textboxes and I am sending the values entered in the textbox to another page using Cache on click of a next button.
Now I have a problem that when the user goes to the next page ad decides to go back again he should be able to do so and the values he entered in the textboxes should still be present.
Is there a way to do so...
My code for sending values is:
protected void Button4_Click(object sender, EventArgs e)
{
if (TextBox2.Text == "" || TextBox3.Text == "")
{
Label1.Text = ("*Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
Cache["PolicyName"] = TextBox2.Text;
Cache["PolicyDesc"] = TextBox3.Text;
Response.Redirect("~/Addnewpolicy3.aspx");
}
}
and I receive this by on the next page as:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string pn = Cache["PolicyName"].ToString();
string pd = Cache["PolicyDesc"].ToString();
string os = Cache["OperatingSystem"].ToString();
}
}
It sounds like you want to take adavantage of Cross-Page postbacks which were added to ASP.NET in version 2.0
The following URL should offer some guidance
http://msdn.microsoft.com/en-us/library/ms178139.aspx
Cache is shared by all users. The code above will result in information being shared between users. If you want per-user temp storage you should use the Session instead. Other than that I can make 2 recommendations:
Proceed with Session, your approach is fine
Look at the Wizard control http://msdn.microsoft.com/en-us/magazine/cc163894.aspx
To make the values restore, in the controls simple do this:
<asp:TextBox ID="txtName" runat="server" text='<%=Session["Name"] %>'></asp:TextBox>
Pretend you got two pages, page1 and page2:
1st you search on page1 and get the result, then click into the link and enter 2nd page.
My suggestion is when you click on hyperlink/button on page1, you can put the textbox field value into session like
Session["key"] = txtbox.Text;
After you enter 2nd page, you can try to set session equal to itself in "Back" button action for bring back to page1.
Session["key"] = Session["key"].ToString();
Insert the code when you back from page2, get value from session and put into search form's textbox
txtbox.Text = Session["key"].ToString();
textbox1.text=1;
My question is, I want to have by default the textbox1 value 1 and then increment it in the record by default.
Not sure if I understood what you want but if you need your textbox to always default to 1 you should create your own textbox class extending the UI.TextBox (don't know if you are in Web or Win).
Something like this:
public class MyTextBox : TextBox
{
private string text = "1";
public override string Text
{
get {return text;}
set {text = value};
}
}
Not sure if i understood you correctly. Not sure whetehr its web or win either.
I am just rewriting what i understood "There is a default textbox whose value should be 1, and for the rest of the records from database more textboxes should come dynamically with values for it incremented by 1 from previous"
If its web you can use some javascript to initialize a variable to 1. Then while generating textboxes you probably can set its value with variable value and increment the variable value for next record.
You have many options:
1. Setting it in design mode. Like this,
<asp:TextBox ID="txtName" Text="1" runat="server"></asp:TextBox>
Setting it in you code behind in the Page_Load event handler. Like this
protected void Page_Load(object sender, EventArgs e) {
txtName.Text = "1";
}
But you should remember to convert these values to integer before incrementing it. Like this
int myValue = Convert.ToInt32(txtName.Text);
Then you can increment it and assign it back to the textbox.
There are other option available like the OnInit event handler. I guess this will do.