【问题标题】:ASP.net Drop Down List Populating More Than Once on RefreshASP.net 下拉列表在刷新时多次填充
【发布时间】:2013-08-07 18:10:15
【问题描述】:

对于这个琐碎的问题,我很抱歉,但我在 Google 或我的参考书中找不到相关信息,这些信息准确地描述/解决了我的问题。

我在页面上有一些 DropDownList 控件,我使用 SQL 表中的信息填充这些控件。刷新页面时,DropDownLists 不会丢失其旧值,而是将相同的值重新添加到它们中,因此现在它们被双重填充。功能仍然相同,但它使 DropDownList 控件看起来不那么整洁,显然是不需要的。

<asp:DropDownList ID="DropDownList2" runat="server" OnLoad="LoadDutchessSubjects"
            AppendDataBoundItems="true">

我后面代码中的 LoadDutchessSubjects 函数只是从 SQL 表中抓取所有记录并将它们加载到 DDL 中:

public void LoadDutchessSubjects(object sender, EventArgs e)
{
    string connectionString = SqlHelperClass.ConnectionString;
    DataTable subjects = new DataTable();
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        con.Open();
        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM cfhudson_counties ORDER BY County", con);
            adapter.Fill(subjects);
            DropDownList2.DataSource = subjects;
            DropDownList2.DataTextField = "County";
            DropDownList2.DataValueField = "County";
            DropDownList2.DataBind();
        }
        catch (Exception ex)
        {
            DropDownList2.Items.Insert(0, new ListItem("<ERROR: Occured in populating.>", "1"));
        }
        con.Close();
    }
    //Overall.Items.Insert(0, new ListItem("<Select Subject>", "0")); //(dev test)
}

我可以在背后的代码中做些什么来防止这种情况发生吗?这是否与 ASP.net 状态和刷新/服务器端发生了什么有关?也许我们可以把这个问题变成一个更有用和更笼统的解释为什么会发生这种情况,因为我显然不明白这里关于 ASP.net 的一些重要的事情。

【问题讨论】:

  • 如何刷新页面?有回发吗?
  • 我想我真的不知道回发到底是什么。当用户单击页面上的 ASP.net 按钮时,我正在刷新页面,该按钮运行另一个函数,该函数将数据带回加载到页面上。如果需要,我也可以发布。

标签: c# asp.net .net refresh state


【解决方案1】:

不要在回发时重新加载项目。它们被持久化在视图状态中

public void LoadDutchessSubjects(object sender, EventArgs e)
{
    if (IsPostback)
        return;

    string connectionString = SqlHelperClass.ConnectionString;
    DataTable subjects = new DataTable();

【讨论】:

  • 会学习的,非常感谢。我确定这确实是问题所在,这更多是因为我对 ASP.net 生命周期/回发缺乏了解。
猜你喜欢
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
相关资源
最近更新 更多