Please forgive me if this has been asked before or if I am not asking correctly. I am new to programming and working on a school assignment.
Assignment: Create a web application project with 2 textboxes and a button control a) On changing the text in field one the text in field 2 should blank. b) On pressing the button the text from field one should be put in field 2 c) All event should be handled on the server side, so no javascript. (Confirmed this with teacher, NO JAVASCRIPT)
Here is the problem:
The page loads with both blank text boxes. I enter text in textbox1, press ok, page reloads but there is nothing in textbox2 (its supposed to copy contents of textbox1). If I press the submit button again, the text copies to textbox 2 as it should.
If I change the text in textbox1, leave focus, page reloads and blanks box 2 as it should. If I press submit button, it copies the text as it should.
I simply cannot get it to work properly the first time the page is loaded.
Here is the code for default.aspx:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 141px">
<form id="form1" runat="server">
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</p>
</form>
</body>
</html>
And here is the code from default.aspx.vb:
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox2.Text = TextBox1.Text
End Sub
Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = ""
End Sub
End Class
I know that when I am entering text into textbox1 for the first time that it is triggering the event for textchanged, but it seems to be happening in the wrong order that I need.
What am I not doing right?
Please let me know if you need any other information.
Generally speaking, it is incorrect to say "NO JS" because
Postback
is JS-invoked event. With no JS at all it is not possible because you can't causePostback
by typing into textbox. AndTextChange
event happens on postback when Asp.Net determined that content of TB has changed. So if you want to type with postback you need minimal JS as described hereYou need to remove
AutoPostBack
from yourTextBox1
because it causes postback when focus moves from textbox. This is the problem. Your button is never pressed on the first pass hence yourTextBox2.Text = TextBox1.Text
never runs on the first time. Second time you already pressing the button, therefore code works.