如何在页面加载时获取TextBox值?

时间:2016-04-06 17:38:48

标签: c# asp.net session

我使用ASP.NET和C#.NET开发了一个Web应用程序。即使页面刷新,我的客户也希望页面保存数据。所以,我试图读取Textbox值并放入会话但在页面加载事件中我发现TextBox为空。 这是我正在尝试的:

protected void Page_Load(object sender, EventArgs e)
{
    Session["name"] = txtName.Text.Trim();
}

我也试过这个:

if (!IsPostBack)
{
    Session["name"] = txtName.Text.Trim();
}

但仍然一样。

2 个答案:

答案 0 :(得分:0)

如果你想实现这样的东西,你可能只想在发生PostBack时设置Session变量,如果它是页面的初始加载,检查Session值是否存在并使用它代替。

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    { 
         // This page is initially being loaded, check the Session
         // and use it
         txtName.Text = Convert.ToString(Session["name"]);
    }
    else
    {
         // It's not a Postback, so store the value for later use
         Session["name"] = txtName.Text.Trim();
    } 

    // Your other code here
}

您可能还希望确保实际上有一个触发PostBack的事件,以确保实际设置了Session变量。此事件甚至可能是TextChanged控件上的txtName事件(只需确保AutoPostBack属性设置为true

<asp:TextBox ID="txtName" runat="server" AutoPostBack="True" OnTextChanged="txtName_TextChanged">

答案 1 :(得分:0)

试试这个:

protected void Page_Load(object sender, EventArgs e)
{
  if (IsPostBack) {
    if(Session["name"] == null)
      Session["name"] = txtName.Text.Trim();
  else
   txtName.Text = Session["name"].ToString() 
  }
}
相关问题