Reputation: 29
I want to create simple button which will swap string value everytime its get clicked. Here are my aspx and aspx.cs file. Aspx:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="switch.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Switch" Text="Switch" CssClass="btn btn-default" />
</div>
Translator From :<asp:Label runat="server" ID="testing"></asp:Label>
Translator To :<asp:Label runat="server" ID="testing1"></asp:Label>
</asp:Content>
aspx.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
public partial class _Default : Page
{
public void SwapStrings(ref string s1, ref string s2)
// The string parameter is passed by reference.
// Any changes on parameters will affect the original variables.
{
string temp = s1;
s1 = s2;
s2 = temp;
System.Console.WriteLine("Inside the method: {0} {1}", s1, s2);
testing.Text = s1;
testing1.Text = s2;
}
public void Switch(object sender, EventArgs e)
{
string str1 = "en";
string str2 = "ja";
System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);
SwapStrings(ref str1, ref str2);
}
}
All I want to do is everytime i click the button, the value for "from" and "to" swapped. However the code now is only effect on the first click. I think the code must have some kind of memory to be able to save the last value. Can anybody help with the code?
Upvotes: 1
Views: 497
Reputation: 89
Use page load for set default values and check ispostback when you hit the swtch button then switch the values;
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
testing.Text = "en";
testing1.Text = "ja";
}
}
protected void Switch(object sender, EventArgs e)
{
string tempLanguage = testing1.Text;
testing1.Text = testing.Text;
testing.Text = tempLanguage;
}
}
Upvotes: 1
Reputation: 48415
It is because you are always starting with the same str1
and str2
values. You need to get the current label values instead of the fixed ones.
Try changing it to this in the Swicth
method:
string str1 = testing.Text;
string str2 = testing1.Text;
On a side note there is no point in passing by reference in this case, you are not doing anything with the original variables after he method call.
Upvotes: 1