Get current TextBox Text value in a button onClick event - asp.net - asp.net

I have such a page
<form runat="server" id="NewForm">
Name: <asp:TextBox ID="Name" runat="server"></asp:TextBox>
<asp:Button ID="AddNewName" runat="server" Text="Add" OnClick="AddNewName_Click" />
<asp:Label ID="NewName" runat="server"></asp:Label>
</form>
In the code behind, I have a Page_Load which assign a value to the TextBox Name.
protected void Page_Load(object sender, EventArgs e)
{
Name.Text = "Enter Your Name Here";
}
Then upon the Click on the button AddNewName, I will write it in the Label NewName
protected void AddNewDivision_Click(object sender, EventArgs e)
{
NewName.Text = Name.Text;
}
But, no matter what I input in the Name TextBox, the Label only displays "Enter Your Name Here". It never updates to the actual content in the Name TextBox. What am I doing wrong with this code?

The problem is that you are always overwriting the changed value in Page_Load. Instead, check the IsPostBack property:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
Name.Text = "Enter Your Name Here";
}

You are re-assigning the text to Name every time Page_Load that over writes the text you entered in TextBox before reach AddNewDivision_Click event. To assign it once on page load and do not over write the subsequent calls you can use Page.IsPostBack property.
if(!Page.IsPostBack)
Name.Text = "Enter Your Name Here";
Or you can assign the text in design html and remove the statement from page_load
<asp:TextBox ID="Name" runat="server" Text="Enter Your Name Here"></asp:TextBox>

Another immediately obvious issue is:
<form runat="server" id="NewForm">
Name: <asp:TextBox ID="Name" runat="server"></asp:TextBox>
<asp:Button ID="AddNewName" runat="server" Text="Add" **OnClick="AddNewName_Click"** />
<asp:Label ID="NewName" runat="server"></asp:Label>
</form>
Not the asterisks above. Then, you were wondering why this didn't run:
protected void **AddNewDivision_Click**(object sender, EventArgs e)
{
NewName.Text = Name.Text;
}
Again, note the asterisks. You weren't calling the correct void, in fact you were probably calling a void that didn't even exist.

Related

Data binding along with the value in ASP.NET

How do you achive something like below in asp.net?
<asp:Label runat="server" Text="The '<%# CustomValue %>' you assigned."/>
This usually depends on where your Label resides. If it is a stond alone control, not nested inside a repeater, you just set your code in code behind:
Label1.Text = $"The {CustomValue} you assigned.";
If the label is nested inside an ItemTemplate in some sort of Repeater control, you can strongly type it to an objects property:
<asp:Repeater runat="server" ID="MyRepeater" ItemType="WebFormsSandbox.Person">
<ItemTemplate>
<li>
<%#: Item.FirstName %> <%#: Item.LastName %>
</li>
</ItemTemplate>
</asp:Repeater>
and the corresponding code behind:
protected void Page_Load(object sender, EventArgs e)
{
MyRepeater.DataSource = Persons();
MyRepeater.DataBind();
}
IEnumerable<Person> Persons()
{
for (int i = 0; i < 10; i++)
{
yield return new Person { Id= i, FirstName = $"Foo{i}", LastName = $"Bar{i}" };
}
}
This would create a list of links, where you then could do anything with it. Whether this would pop up a custom window or does a postback .. up to you.
If you really want to do it that way, write the string inside the server tags.
<asp:Label runat="server" Text='<%# "The " + CustomValue + " you assigned." %>'/>
However if the Label is not inside a GridView, Repeater etc you have to call DataBind manually.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
You would typically do this in the code behind on page load, unless you were using a datagrid or repeater control. Assign an ID to your control and reference it like so.
<asp:Label runat="server" ID="Label1" />
protected void Page_Load(object sender,EventArgs e)
{
Label1.Text = "Your Value";
}

An incorrect even gets triggered if the browser back button is clicked

Here's my aspx page
<asp:Label runat="server" ID="lbl" Text="suff goes here" /><br />
<asp:Button runat="server" OnClick="btnClick" ID="btn" Text="Click me!" />
<asp:DropDownList runat="server" ID="ddl"
OnSelectedIndexChanged="ddlChanged"
AutoPostBack="true">
<Items>
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</Items>
</asp:DropDownList>
And here's the code behind
protected void btnClick(object sender, EventArgs e)
{
lbl.Text = DateTime.Now.Ticks.ToString();
}
protected void ddlChanged(object sender, EventArgs e)
{
Response.Redirect("Page2.aspx");
}
When I click something in the dropdown, I get redirected to Page2, I then click the browser back button, and click the "Click Me!" btn. Instead of the btnClick even getting fired, it fires ddlChanged first, and does the redirect again.
Can this be solved without javascript?
You can use a session variable and store the last value in the dropdown, so when it fires you are like double-checking that effectively the dropdown.SelectedIndex change
protected void ddlChanged(object sender, EventArgs e)
{
// If the var is NULL then it is the first time the event gets triggered
if (Session["lastDropDownValue"] != null)
//If it has a value, and also is the same selected index, then it really doesn't change
if (Convert.ToInt32(Session["lastDropDownValue"].ToString()) == ddl.SelectedIndex)
return;
//Set your variable for future validations
Session["lastDropDownValue"] = ddl.SelectedIndex;
Response.Redirect("Page2.aspx");
}

Passing a variable from aspx to .cs

I am trying to pass an Id from aspx to .cs. This is the code i have in the aspx:
<asp:Button ID="btnAddAsFriend" runat="server" Text="Add as Friend" onclick="btnAddAsFriend_Click" CommandName = "Id" CommandArgument='<%# Eval("u.UserID.ToString()") %>'/>
The CommandArgument is being set but when i try to read it from the .cs its getting null. This is the code I have in the .cs
protected void btnAddAsFriend_Click(object sender, EventArgs e)
{
string id = ((Button)sender).CommandArgument;
}
Thanks

ASP.NET Textbox AutoPostBack Not Firing

After searching I've found a number of suggestions, but none of them are fixing the issue.
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text=""></asp:TextBox>
In the properties window, EnableViewState = True for the TextBox (Suggested here). I am typing a new value into the TextBox and then hitting the Tab key. Nothing happens nor does the break point at if(IsPostBack...) break.
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && uid.Text != "" && pw.Text == "")
{
Do stuff
}
}
UPDATE: Other TextBox setups I've tried:
<asp:TextBox runat="server" ID="uid" Text="" AutoPostBack="True" OnTextChanged="UidTextChanged"></asp:TextBox>
protected void UidTextChanged(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('it works');", true);
}
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');" OnTextChanged="UidTextChanged"></asp:TextBox>
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');"></asp:TextBox>
Whenever AutoPostBack is set to true, I receive the following error in the browser console:
"Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function
__doPostBack
(anonymous function)"
When I have the onblur property set, I receive the exact same error except instead of anonymous function it says onblur.
You could add a javascript event to the onblur for it. onblur='__doPostBack('','');'
That would cause your text box to cause a postback once it is tabbed out of.
Edit: It should be " not ' <asp:TextBox ID="TextBox1" runat="server" onblur="__doPostBack('','');" /> Just tried that and it works. Try removing the AutoPostBack="True"
Edit 2: Base on your pastebin....
<asp:Button runat="server" UseSubmitBehavior="True" ID="submit" Text="Save"
onclick="SubmitClick"/>
You can't have an ID of "submit". Change that to "btnSubmit" and the Javascript solution will work and I bet the Auopostback solution will too.
http://www.xpertdeveloper.com/2012/05/property-submit-of-object-is-not-a-function/ will explain the problem.
You can add OnTextChanged="TextBox1_TextChanged" on your textBox
Nota : It's important to set event fire, no just AutoPostBack="true".
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Code Behind:
protected void TextBox1_TextChanged(object sender, System.EventArgs e) {
.....
}

ASP.Net: Ajax registration question

I worked with: ASP.Net: Ajax check for registration as a user?
It has a few errors, I don't understand:
1) It worked only one time for one textbox. If the textbox is edited a second time, the breakpoint will not be hited. Why?
2) For my Email, I have a check, that there is no duplicate, when there is one, there should the set an error panel visible, but it don't show.
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
}
When the update mode is conditional
<asp:scriptmanager runat="server" id="sm1" />
<asp:updatepanel runat="server" id="up1" updatemode="Conditional"> // here the updatemode is conditional ...
<contenttemplate>
<asp:textbox runat="server" id="tbUsername" autopostback="true" ontextchanged="tbUsername_TextChanged" />
<asp:customvalidator runat="server" text="Email already used" id="cusValEmail" />
<asp:textbox runat="server" id="tbPassword" />
</contenttemplate>
</asp:updatepanel>
You need to call
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
up1.Update(); // call to update the update panel "up1"
}
Sorry I'm a bit rusty, it's a while since I've used update panels.
After an update panel updates you must reinitialise the javascript on the html elements inside it.
So, to the end of your method you could add:
protected void txtEMail_TextChanged(object sender, EventArgs e)
{
Business.UserHandling uh = new Business.UserHandling();
if (uh.CheckIfEmailExists(txtEMail.Text))
{
panelHelp.Visible = true;
lblHelp.Text = "EMail existriert schon.";
}
// Re-init javascript
ScriptManager.RegisterStartupScript(Type, String, "add onchange js here", Boolean);
}
see http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

Resources