How do you use if (IsPostBack) in ASP.NET C#
-
12-11-2019 - |
Question
How can I used if (IsPostBack){}
to display user's names from two text boxes into another text box?
I have 3 text boxes and a button. The text boxes are named txtLastName, txtGivenName, txtOutput. My button is btnSubmit.
How can I display text from the txtLastName and txtGivenName in the txtOutput text box?
How can I display it as: First (space) Lastname or Last, Firstname in this code.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
Solution
How can I display text from the txtLastName and txtGivenName in the txtOutput text box?
- Go to the design of your page.
- Click the button.
- Click F4 or Right click and select properties. This will show you a window for button.
- Click the event.
- Double click the "Click" action.
- This will navigate you to the code behind.
- Write the code in this handler
- This is how the design will look like for your event handler
protected void btnSubmit_Click(object sender, EventArgs e)
{
txtOutput.Text = string.Format("{0} {1}", txtGivenName.Text, txtLastName.Text);
}
How can I display it as: First (space) Lastname or Last, Firstname in this code.
Write down the code in the handler as below.
txtOutput.Text = txtLast.Text + ", " + txtFirst.Text;
OTHER TIPS
Create an event handler for the Click event on the button and then in the code behind, do like this:
protected void btnSubmit_Click(object sender, EventArgs e)
{
txtOutput.Text = string.Format("{0} {1}", txtGivenName.Text, txtLastName.Text);
}
Why don't use use the submit button method to achieve this?
protected void btnSubmit_Click(object sender, System.EventArgs e)
{
txtOutput.Text = txtLast.Text + ", " + txtFirst.Text;
}
try this
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
txtOutput.Text = txtLastName.Text + " " + txtLastName.Text;
}