【问题标题】:ASP.net c# - Different modes for redirecting user Edit and Add NewASP.net c# - 重定向用户的不同模式编辑和添加新
【发布时间】:2012-11-26 07:35:14
【问题描述】:

我有一个表格,可以带回数据库中的客户列表。还有一个添加客户按钮来添加一个新客户和一个用户可以编辑现有客户的超链接。单击编辑链接时,我可以为该客户恢复正确的数据,但如果我进行更改并单击“更新”按钮,它不会编辑现有数据。另一个问题是重定向添加新客户时也会出现“更新”按钮(用户输入新客户的数据并单击“更新”)。是否可以为不同的操作(添加新或编辑)/查询引用不同的代码?这是我到目前为止所拥有的。感谢您的帮助。

<asp:Content ID="Content1" ContentPlaceHolderID="chpContent" runat="server">
<div>
    <h2>Customer Listing</h2>
    <br />
</div>
<p style="text-align:center">
    <asp:Button ID="btnCustomer" class="button" runat="server" Text="Add New Customer" onclick="btnCustomer_Click" />
</p>

<asp:ListView ID="lv" runat="server" 
    onselectedindexchanged="lv_SelectedIndexChanged">
<LayoutTemplate>
  <table width="110%" class="TableListing">
  <tbody>
    <thead>
    <th width="150">Customer Name</th>
      <th width="150">Email</th>
      <th width="150">City</th>
      <th width="40">State</th>
      <th width="110">Phone</th>
      <th width="80">Modify</th>
    </thead>
    <tr id="itemPlaceholder" runat="server"></tr>
     </tbody>
    </table>  

    <asp:DataPager ID="ItemDataPager" runat="server" PageSize="20">
        <Fields>
            <asp:NumericPagerField ButtonCount="5" />
        </Fields>
    </asp:DataPager>

</LayoutTemplate>

<ItemTemplate>
    <tr>
     <td><%# Eval ("LastName") %>, <%# Eval ("FirstName") %></td>
     <td><%# Eval ("Email") %></td>
     <td><%# Eval ("City") %></td>
     <td><%# Eval ("State") %></td>
     <td><%# Eval ("Phone") %></td>
     <td>
        <asp:HyperLink ID="lnkEdit" runat="server" NavigateUrl='<%# "CustomerEdit.aspx?ID=" + Eval("CustomerID") %>' Text="Edit" />
    </td>
    </tr>
</ItemTemplate>

这是我的 CustomerEdit.aspx 页面:

public partial class CustomerEdit : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Master.HighlightNavItem("Customers");

        int CustomerID = Int32.Parse(Request.QueryString["ID"]);

        //Declare the connection object
        SqlConnection Conn = new SqlConnection();
        Conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;

        //Connect to the db
        Conn.Open();

        //Define query
        string sql = "SELECT * FROM Customer where CustomerID=@CustomerID";

        //Declare the Command
        SqlCommand cmd = new SqlCommand(sql, Conn);

        //Add the parameters needed for the SQL query
        cmd.Parameters.AddWithValue("@CustomerID", CustomerID);

        //Declare the DataReader
        SqlDataReader dr = null;

        //Fill the DataReader
        dr = cmd.ExecuteReader();

        //Get the data
        if (dr.Read() == false)
            {
                //No Records
                dr.Close();
                Conn.Close();
                return;
            }

    txtFirstName.Text = dr["FirstName"].ToString();
    txtLastName.Text = dr["LastName"].ToString();
    txtEmail1.Text = dr["Email"].ToString();
    txtEmail2.Text = dr["Email"].ToString();
    txtPassword1.Text = dr["Password"].ToString();
    txtPassword2.Text = dr["Password"].ToString();
    txtAddress1.Text = dr["Address1"].ToString();
    txtAddress2.Text = dr["Address2"].ToString();
    txtCity.Text = dr["City"].ToString();
    txtState.Text = dr["State"].ToString();
    txtZip.Text = dr["Zip"].ToString();
    txtPhone.Text = dr["Phone"].ToString();
    txtFax.Text = dr["Fax"].ToString();


    dr.Close();
    Conn.Close();

    }


    protected void btnCancel_Click1(object sender, EventArgs e)
    {
        Response.Redirect("Customers.aspx");
    }


    protected void btnUpdate_Click(object sender, EventArgs e)
    {

        int CustomerID = Int32.Parse(Request.QueryString["ID"]);

        //Declare the connection object
        SqlConnection Conn = new SqlConnection();
        Conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;

        //Connect to the db
        Conn.Open();


        //Define query
        string sql = "UPDATE Customer SET Fax=@Fax Where CustomerID=@CustomerID";

        //Declare the Command
        SqlCommand cmd = new SqlCommand(sql, Conn);

        //Add the parameters needed for the SQL query
        cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
        cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
        cmd.Parameters.AddWithValue("@Email", txtEmail1.Text);
        cmd.Parameters.AddWithValue("@Password", txtPassword1.Text);
        cmd.Parameters.AddWithValue("@Address1", txtAddress1.Text);
        cmd.Parameters.AddWithValue("@Address2", txtAddress2.Text);
        cmd.Parameters.AddWithValue("@City", txtCity.Text);
        cmd.Parameters.AddWithValue("@State", txtState.Text);
        cmd.Parameters.AddWithValue("@Zip", txtZip.Text);
        cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
        cmd.Parameters.AddWithValue("@Fax", txtFax.Text);

        //Execute the query
        int NumRows = 0;
        NumRows = cmd.ExecuteNonQuery();

        Conn.Close();

        lblUpdate.Text = "Updated " + NumRows.ToString() + " record";

    }

}

}

还有我的 Customers.aspx.cs 页面,用户被重定向到该页面。

    public partial class Customers : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {      
          this.Master.HighlightNavItem("Customers");


        //Declare the connection object
        SqlConnection Conn = new SqlConnection();
        Conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;

        //Connect to the db
        Conn.Open();

        //Define query
        string sql = "SELECT CustomerID, LastName, FirstName, Email, Password, Address1, Address2, City, State, Zip, Phone, Fax FROM Customer";

        //Declare a SQL Adapter
        SqlDataAdapter da = new SqlDataAdapter(sql, Conn);

        //Declare a DataTable
        DataTable dt = new DataTable();

        //Populate the DataTable
        da.Fill(dt);

        //Bind the Listview
        lv.DataSource = dt;
        lv.DataBind();

        dt.Dispose();
        da.Dispose();
        Conn.Close();

    }

            protected void btnCustomer_Click(object sender, EventArgs e)
         {
              Response.Redirect("CustomerEdit.aspx");                

          }

            protected void lv_SelectedIndexChanged(object sender, EventArgs e)
            {
                Response.Redirect("CustomerEdit.aspx");
            }

}

}

【问题讨论】:

    标签: c# asp.net sql


    【解决方案1】:

    更新不起作用,因为您覆盖了 PageLoad 上的数据。使用IsPostBack 来避免这种情况:

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Master.HighlightNavItem("Customers");
    
        if(!IsPostBack)
        {
            int CustomerID = Int32.Parse(Request.QueryString["ID"]);
    
            //Declare the connection object
            SqlConnection Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
    
            //Connect to the db
            Conn.Open();
    
            //Define query
            string sql = "SELECT * FROM Customer where CustomerID=@CustomerID";
    
            //Declare the Command
            SqlCommand cmd = new SqlCommand(sql, Conn);
    
            //Add the parameters needed for the SQL query
            cmd.Parameters.AddWithValue("@CustomerID", CustomerID);
    
            //Declare the DataReader
            SqlDataReader dr = null;
    
            //Fill the DataReader
            dr = cmd.ExecuteReader();
    
            //Get the data
            if (dr.Read() == false)
                {
                    //No Records
                    dr.Close();
                    Conn.Close();
                    return;
                }
    
            txtFirstName.Text = dr["FirstName"].ToString();
            txtLastName.Text = dr["LastName"].ToString();
            txtEmail1.Text = dr["Email"].ToString();
            txtEmail2.Text = dr["Email"].ToString();
            txtPassword1.Text = dr["Password"].ToString();
            txtPassword2.Text = dr["Password"].ToString();
            txtAddress1.Text = dr["Address1"].ToString();
            txtAddress2.Text = dr["Address2"].ToString();
            txtCity.Text = dr["City"].ToString();
            txtState.Text = dr["State"].ToString();
            txtZip.Text = dr["Zip"].ToString();
            txtPhone.Text = dr["Phone"].ToString();
            txtFax.Text = dr["Fax"].ToString();
    
    
            dr.Close();
            Conn.Close();
        }
    
    }
    

    【讨论】:

    • 谢谢。我这样做了,但我收到错误“必须在 NumRows = cmd.ExecuteNonQuery() 的 btnUpdate 下的代码中声明标量变量“@CustomerID”;我不明白这是什么意思。CustomerID 不是在“int CustomerID = Int32.Parse(Request.QueryString["ID"]);
    • 因为您没有将其添加为参数。
    • 是的,就是这样。谢谢你。现在我的问题的另一部分是关于使用 EditCustomer.aspx 页面来添加新客户和编辑现有客户。在 btnUpdate 事件中,如何根据是新客户还是现有客户来区分使用哪个查询?
    • @user1576304 添加标志,或使用不同的按钮,思考和设计一些东西。
    • @user1576304 我首先回答了更新问题。现在 Mode=N 和 Mode=E 是一种方法。
    猜你喜欢
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2011-04-03
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多