ASP.Net DropDownList保留数据库中的值 - AutoPostBack

时间:2014-10-20 03:22:18

标签: sql asp.net autopostback

我一直坚持这个问题,在线搜索,但没有解决方案,但解决了我的问题。我有一个下拉列表,它根据在文本字段中输入的邮政编码从我的数据库中的表中检索计划名称。我遇到的问题是:当我输入邮政编码时,计划名称在下拉列表中填充没有问题,然后我选择其中一个计划,当我进一步尝试在其他具有autppostback的字段中输入其他信息时= true,下拉列表不保留其值并始终选择第一个值,我希望下拉列表在回发后保留选定的值,这是我的代码:

step1.aspx

<p>
    <asp:TextBox ID="txt_zip_code" runat="server" AutoPostBack="true"></asp:TextBox>
</p>
<p>    
    <asp:DropDownList ID="dd_dental_plan" runat="server" EnableViewState="true">
</asp:DropDownList>

</p>

step1.cs

 protected void Page_Load(object sender, EventArgs e)
    {

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString))
        {
            using (SqlCommand sqlCmd = new SqlCommand())
            {
                sqlCmd.CommandText = "SELECT * FROM [dbo].[mfd_plans] WHERE zip_code = @zipCode";
                sqlCmd.Parameters.AddWithValue("@zipCode", txt_zip_code.Text);

                sqlCmd.Connection = conn;
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dd_dental_plan.DataSource = dt;
                dd_dental_plan.DataValueField = "plan_id";
                dd_dental_plan.DataTextField = "plan_name";
                dd_dental_plan.DataBind();
                conn.Close();
                dd_dental_plan.Items.Insert(0, new ListItem("Please select plan", "0"));
            }
        }

2 个答案:

答案 0 :(得分:2)

您应该在aspx页面上使用更新面板,以防止从其他字段发生自动后备时整个页面加载。 只需在页面上放置一个asp:scriptmanager控件。将您的邮政编码和下拉列表放入更新面板后,将其他控件放在单独的更新面板中,通过该面板进行回发。你的代码看起来像这样。

  <asp:ScriptManager runat="server">
  </asp:ScriptManager>
  <div>
  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <p>
            <asp:TextBox ID="txt_zip_code" runat="server" AutoPostBack="true"></asp:TextBox>
        </p>
        <p>    
             <asp:DropDownList ID="dd_dental_plan" runat="server" EnableViewState="true">
            </asp:DropDownList>

        </p>
    </ContentTemplate>
    </asp:UpdatePanel>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
            another controls which caused postback event
    </ContentTemplate>
    </asp:UpdatePanel>
    another controls which don't cause postback.
</div>

希望这会有效。enter code here

由于

答案 1 :(得分:0)

嗯,我真的希望我能正确理解你的问题。 你尝试过像

这样的东西吗?
    if (!Page.IsPostBack)
    {// All the code that you've written above ..}

并使用您在Page_Load中编写的所有代码执行此操作... 试一试......

相关问题