1

我用以下内容填充我的texbox:

foreach (User u in userInfo)
{
    txtNickname.Text = u.Nickname;
    txtFirstName.Text = u.FirstName;
    txtLastName.Text = u.LastName;
    txtEmail.Text = u.Email;
}

我的文本框现在充满了数据库中的数据。

例如,我在所有 texboxes 中填充新值并单击按钮,然后发生以下情况:

if (txtNickname.Text != String.Empty && txtFirstName.Text != String.Empty && txtLastName.Text != String.Empty && txtEmail.Text != String.Empty)
{
   //TODO
}

但是当我调试时:文本框的值是旧值(来自 foreach 循环的值),而不是我填写在文本框中的新值。

为什么会这样?我正在从文本框中的数据库中加载一些数据,之后我自己更改了文本框的值,当我调试文本框的值仍然是数据库值(请参阅 foreach 循环)。

4

1 回答 1

3

如果第一个循环是在 Page_Load 事件中执行的,那么您应该确保在由于单击按钮而返回页面时不会再次执行。

MSDN 上的Page.IsPostBack中的更多信息

private void Page_Load()
{
    if (!IsPostBack)
    {
        // This code should be executed only when the page is being 
        // rendered for the first time not when is responding to a postback 
        // raised by the <runat="server">  controls
        UserInfoCollection userInfo = GetUserInfoCollection();

        foreach (User u in userInfo)
        {
            txtNickname.Text = u.Nickname;
            txtFirstName.Text = u.FirstName;
            txtLastName.Text = u.LastName;
            txtEmail.Text = u.Email;
        }
    }
}
于 2013-07-19T17:23:19.647 回答