2013-05-20 44 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;