0

我有一个网络表单,它的行为与我预期的不一样,我有点难过。在表单上,​​电话号码从数据库填充到文本框。这部分工作正常。然后,用户可以选择编辑文本框中的值,并按下一个按钮,将数据库中的值更新为文本框中的值。这是不工作的部分。

这是我的代码。

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class contact_edit : System.Web.UI.Page
{
    //sql connection here

    protected void Page_Load(object sender, EventArgs e)
    {
        string phoneNum = "";
        cn.Open();
        SqlCommand command = new SqlCommand("getContactInfo", cn);
        command.CommandType = CommandType.StoredProcedure;

        SqlDataReader myReader;
        myReader = command.ExecuteReader();

        while (myReader.Read())
        {
            phoneNum = myReader.GetString(3).ToString();
        }

        cn.Close();

        //If I take this part out and don't populate textbox,
        //my update works.  If I leave it, it does not
        phone.Text = phoneNum.ToString();

    }
    protected void update_btn_Click(object sender, EventArgs e)
    {
        cn.Open();

        phone.Text = "";

        string updatedPhone = phone.Text;

        string updateSQLString = "update contact set Phone_num = '" + updatedPhone +   
        "'";

        SqlCommand updateCommand = new SqlCommand(updateSQLString, cn);
        updateCommand.ExecuteNonQuery();

        cn.Close();
        Response.Redirect("contact_edit.aspx");
}

}

当我按下按钮调用我的更新方法时。它尝试获取电话文本框的值。但是在表单加载之后,我更改了文本框的值,然后点击了更新按钮,它一直在获取表单加载时最初分配给文本框的值。为什么会这样?

4

3 回答 3

0

尝试放置if (!Page.IsPostBack)您的 page_load 代码

protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack)
        {
        string phoneNum = "";
        cn.Open();
        SqlCommand command = new SqlCommand("getContactInfo", cn);
        command.CommandType = CommandType.StoredProcedure;

        SqlDataReader myReader;
        myReader = command.ExecuteReader();

        while (myReader.Read())
        {
            phoneNum = myReader.GetString(3).ToString();
        }

        cn.Close();

        //If I take this part out and don't populate textbox,
        //my update works.  If I leave it, it does not
        phone.Text = phoneNum.ToString();
     }

    }
于 2013-07-05T22:38:17.230 回答
0

为什么会这样?

因为您在每次回发时都从数据库中加载值。将其包装在IsPostBack-check 中:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        // only load the value on the first load
    }
}
于 2013-07-05T22:38:41.640 回答
0
protected void Page_Load(object sender, EventArgs e)
{

  if (!Page.IsPostBack)
  {
     //access data here
     //assign value here
     phone.Text = phoneNum.ToString();  
  }

}   
于 2013-07-05T22:43:17.167 回答