错误:从按钮单击事件的页面上的控件获取值

时间:2012-05-30 15:11:55

标签: asp.net

下面的代码只是从数据库中获取数据并将数据填充到asp.net页面上的TextBoxes中,当我单击按钮btnSave时,TextBox上的任何更改都会反映到数据库。 但是,当我单击btnSave按钮时,我从文本框中获取的值是Page_Load事件中的初始值,而不是我在Textboxes上更改值后的值

public partial class Settings : System.Web.UI.Page
{
    string conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;    

    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(conString);
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT CompanyAUserName, CompanyAPassword, CompanyAEmail, CompanyBUserName, CompanyBPassword, AgentAName, AgentBName, ItemShortageNotification FROM COMPANY_SETTINGS", con);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            txtHostName.Text =  dr["CompanyAUserName"].ToString();
            txtHostPassword.Text = dr["CompanyAPassword"].ToString();
            txtHostEmail.Text = dr["CompanyAEmail"].ToString();
            txtClientName.Text = dr["CompanyBUserName"].ToString();
            txtClientPassword.Text = dr["CompanyBPassword"].ToString();
            txtAgentAName.Text = dr["AgentAName"].ToString();
            txtAgentBName.Text = dr["AgentBName"].ToString();
            txtItemQty.Text = dr["ItemShortageNotification"].ToString();            
        }
        con.Close();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {        
        SqlConnection con = new SqlConnection(conString);
        con.Open();                
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;        
        try
        {
            cmd.CommandText =
            "UPDATE COMPANY_SETTINGS SET CompanyAUserName = @CompanyAUserName, CompanyAPassword = @CompanyAPassword, CompanyAEmail = @CompanyAEmail, CompanyBUserName = @CompanyBUserName, CompanyBPassword = @CompanyBPassword, AgentAName = @AgentAName, AgentBName = @AgentBName, ItemShortageNotification = @ItemShortageNotification";
            cmd.Parameters.AddWithValue("@CompanyAUserName", txtHostName.Text);
            cmd.Parameters.AddWithValue("@CompanyAPassword", txtHostPassword.Text);
            cmd.Parameters.AddWithValue("@CompanyAEmail", txtHostEmail.Text);
            cmd.Parameters.AddWithValue("@CompanyBUserName", txtClientName.Text);
            cmd.Parameters.AddWithValue("@CompanyBPassword", txtClientPassword.Text);
            cmd.Parameters.AddWithValue("@AgentAName", txtAgentAName.Text);
            cmd.Parameters.AddWithValue("@AgentBName", txtAgentBName.Text);
            cmd.Parameters.AddWithValue("@ItemShortageNotification", txtItemQty.Text.Trim());
            cmd.ExecuteNonQuery();
            Response.Redirect("~/Settings.aspx");
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('Error: " + ex.Message + "')</script>");            
        }        
        con.Close();        
    }
}

以下是.aspx页面

的部分代码
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolderBody" Runat="Server">
    <div style="height:100%;" runat="server" id="divSettings">        
        <h3 style="padding:0; margin:0">Settings</h3>
        <h5 style="padding: 5px">(This page is only visible to the host)</h5>
        <table class="SignUpTable" runat="server">
            <tr runat="server">
                <td align="center" colspan="2" runat="server">
                    <h1>Company A Information</h1>
                    <p>This is host account infromation. </p>
                </td>
            </tr>
            <tr runat="server">
                <td class="label" runat="server" >
                    <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserNameLabel">User Name: </asp:Label><br />
                    <div class="small"> Minimun of 4 characters </div>
                </td>
                <td runat="server">
                    <asp:TextBox ID="txtHostName" runat="server" CssClass="textBox"></asp:TextBox><br />
                    <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" 
                        ControlToValidate="txtHostName" Text="Host name is required." 
                        ToolTip="Enter Host Name" Display="Dynamic" 
                        ValidationGroup="ValidationSettings" SetFocusOnError="True"/>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" SetFocusOnError="True"
                            runat="server" ControlToValidate="txtHostName" Display="Dynamic" 
                        ValidationExpression="[0-9a-zA-Z]{4,}" ValidationGroup="ValidationSettings">Host name must be more than 4 characters.</asp:RegularExpressionValidator>
                </td>
            </tr> 

我尝试使用FindControl()并仍然获得相同的值。 请告诉我我错过了什么。谢谢。

4 个答案:

答案 0 :(得分:2)

更改代码以将检查添加到IsPostBack。发生的事情是你在btn_Save事件触发之前加载数据。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
       loadData();
}

private void loadData()
{

    SqlConnection con = new SqlConnection(conString);
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT CompanyAUserName, CompanyAPassword, CompanyAEmail, CompanyBUserName, CompanyBPassword, AgentAName, AgentBName, ItemShortageNotification FROM COMPANY_SETTINGS", con);
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        txtHostName.Text =  dr["CompanyAUserName"].ToString();
        txtHostPassword.Text = dr["CompanyAPassword"].ToString();
        txtHostEmail.Text = dr["CompanyAEmail"].ToString();
        txtClientName.Text = dr["CompanyBUserName"].ToString();
        txtClientPassword.Text = dr["CompanyBPassword"].ToString();
        txtAgentAName.Text = dr["AgentAName"].ToString();
        txtAgentBName.Text = dr["AgentBName"].ToString();
        txtItemQty.Text = dr["ItemShortageNotification"].ToString();            
    }
    con.Close();
}

答案 1 :(得分:1)

您不应该在每次回发时从数据库加载,但仅限于!Page.IsPostback

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        // do the databinding ....
    }
}

旁注:您应该将using-statement用于实施IDisposable的任何内容,尤其是Connections。您不需要关闭它,即使dispose中出现异常,它也会被关闭。

using(SqlConnection con = new SqlConnection(conString))
{
    con.Open();
    using(SqlCommand cmd = new SqlCommand("SELECT CompanyAUserName, CompanyAPassword, CompanyAEmail, CompanyBUserName, CompanyBPassword, AgentAName, AgentBName, ItemShortageNotification FROM COMPANY_SETTINGS", con))
    {
        // ...
    }
}

答案 2 :(得分:1)

您需要添加回发检查:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        SqlConnection con = new SqlConnection(conString);
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT CompanyAUserName, CompanyAPassword,         CompanyAEmail, CompanyBUserName, CompanyBPassword, AgentAName, AgentBName,         ItemShortageNotification FROM COMPANY_SETTINGS", con);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            txtHostName.Text =  dr["CompanyAUserName"].ToString();
            txtHostPassword.Text = dr["CompanyAPassword"].ToString();
            txtHostEmail.Text = dr["CompanyAEmail"].ToString();
            txtClientName.Text = dr["CompanyBUserName"].ToString();
            txtClientPassword.Text = dr["CompanyBPassword"].ToString();
            txtAgentAName.Text = dr["AgentAName"].ToString();
            txtAgentBName.Text = dr["AgentBName"].ToString();
            txtItemQty.Text = dr["ItemShortageNotification"].ToString();            
        }
        con.Close();
    }
}

答案 3 :(得分:1)

你的错误是遗漏了!Page.IspostBack。

因此,只要您尝试保存,就会重新填充文本框并获取值。