C# ASP.net下拉列表在刷新时多次填充

C# ASP.net下拉列表在刷新时多次填充,c#,asp.net,.net,refresh,state,C#,Asp.net,.net,Refresh,State,我很抱歉这个琐碎的问题,但我无法在谷歌上或在我的参考书中找到相关信息,这些信息准确地描述/解决了我的问题 我在一个页面上有一些DropDownList控件,我用SQL表中的信息填充这些控件。刷新页面时,DropDownLists不会丢失它们的旧值,而是将相同的值重新添加到它们中,因此现在它们是双重填充的。所有的功能都是一样的,但它使DropDownList控件看起来不那么整洁,显然是不需要的 <asp:DropDownList ID="DropDownList2" runat="serve

我很抱歉这个琐碎的问题,但我无法在谷歌上或在我的参考书中找到相关信息,这些信息准确地描述/解决了我的问题

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

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

my code behind中的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)
}
public void LoadDutchessSubjects(对象发送方,事件参数e)
{
string connectionString=SqlHelperClass.connectionString;
DataTable主题=新DataTable();
使用(SqlConnection con=newsqlconnection(connectionString))
{
con.Open();
尝试
{
SqlDataAdapter=新SqlDataAdapter(“从cfhudson_Countries ORDER BY County中选择*”,con);
a.填写(受试者);
DropDownList2.DataSource=受试者;
DropDownList2.DataTextField=“County”;
DropDownList2.DataValueField=“County”;
DropDownList2.DataBind();
}
捕获(例外情况除外)
{
DropDownList2.Items.Insert(0,新列表项(“,”1”);
}
con.Close();
}
//插入(0,新列表项(“,“0”);/(开发测试)
}

我可以在代码背后做些什么来防止这种情况发生吗?这与ASP.net状态和刷新/服务器端发生了什么有关吗?也许我们可以将这个问题转化为一个更有用、更一般的解释,解释为什么会发生这种情况,因为我显然不了解ASP.net的一些重要内容。

请勿在回发上重新加载项目。它们被持久保存在viewstate中

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

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

如何刷新页面?有回邮吗?我想我真的不知道回邮到底是什么。当用户单击页面上的ASP.net按钮时,我正在刷新页面,该按钮运行另一个函数,将数据带回页面加载。如果需要的话,我也可以发布。我会学习的,非常感谢。我确信这才是真正的问题所在,这更多是因为我对ASP.net生命周期/回发缺乏了解。