2017-08-16 89 views
1

我想創建一個簡單的按鈕,每次點擊時都會交換字符串值。這是我的aspx和aspx.cs文件。 .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); 
    } 
} 

所有我想要做的就是每次我按一下按鈕,在 「從」 和 「到」 交換價值。但是現在的代碼只對第一次點擊有影響。我認爲代碼必須有某種內存才能保存最後的值。任何人都可以幫助代碼嗎?

回答

1

這是因爲您總是以相同的str1str2值開始。您需要獲取當前標籤值而不是固定值。

嘗試在Swicth方法將其更改爲這樣:

string str1 = testing.Text; 
string str2 = testing1.Text; 

在一個側面說明存在通過引用傳遞在這種情況下沒有意義的,你是不是他的方法調用之後做與原來的變量什麼。

+0

嗨,謝謝你的快速回復。那麼初始值呢?我想從=「en」的第一個值到=「ja」。然後每次點擊交換按鈕 –

+1

只需在aspx文件中直接設置這些默認值:' en' – musefan

1

使用頁面加載設置默認值,並檢查ispostback當你點擊swtch按鈕,然後切換值;

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; 

     } 
    }