2013-05-20 46 views
1

我想用字符串更新文本框。該字符串將被連接,然後通過點擊事件來更新文本框。我可以在Windows應用程序中執行此操作,但是當我嘗試在asp.net應用程序中執行此操作時,我無法獲得我想要的結果。更新文本框的值,然後更多一次在webform asp.net

public partial class WebForm3 : System.Web.UI.Page 
{ 
    public string string_punch; 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     MultiView1.SetActiveView(View1);    
     txt_punch.MaxLength = 4; 
     txt_punch.Attributes.Add("OnChange", string_punch);    
    } 

    protected void btn_punch_7_Click(object sender, EventArgs e) 
    { 
     const string string_punch_Number_7 = "7"; 
     string_punch = string_punch + string_punch_Number_7; 
     txt_punch.Attributes.Add("Value", string_punch); 
    } 

    protected void btn_punch_8_Click(object sender, EventArgs e) 
    { 
     const string string_punch_Number_8 = "8"; 
     string_punch = string_punch + string_punch_Number_8; 
     txt_punch.Attributes.Add("Value", string_punch); 
    } 

我希望能夠點擊btn_punch_7,然後單擊btn_punch_8,並連接字符串,並更新文本框與兩個號碼。每次我點擊一個按鈕,字符串都被設置爲空。感謝您的幫助。

回答

2

string_punchPostBack之間失去了,這就是爲什麼它總是等於null,因爲ASP.NET是無狀態意味着它不會阻止它後狀態恢復後回來。還使用TextBoxText屬性來分配/檢索文本框的值。

更改相應的事件下面的代碼:

protected void btn_punch_7_Click(object sender, EventArgs e) 
{ 
    const string string_punch_Number_7 = "7"; 
    var text = txt_punch.Text; 
    text += string_punch_Number_7 

    txt_punch.Text = text; 
} 
+0

+1表示string_punch失去值。 –

+0

工作正常!謝謝我正要把我的頭髮拉出來。我認爲這是造成這種情況的原因,但我無法弄清楚如何解決這個問題。我有一種感覺,這不是asp.net最後一次會讓我迷惑。 – nate

0

商店string_punchSession,所以這段代碼添加到負載:

if (Session["string_punch"] == null) 
{ 
    // this will only happen ONE TIME per session 
    Session["string_punch"] = "your INITIAL static value"; 
} 
string_punch = Session["string_punch"]; 

現在string_punch值將後背上之間被保留。代碼中發生的事情是當頁面在回發期間重建時,public string string_punch;正在重新定義此變量。

現在,經過每次點擊只需添加這行:

Session["string_punch"] = string_punch; 
+0

我也很好奇。我也會嘗試這一個。謝謝! – nate

0

你的屬性值,每次增加的元素。而不是這樣做。

txt_punch.Text = string_punch;