清除SqlDataAdapter中的数据

时间:2018-03-14 20:10:13

标签: c# asp.net sql-server webforms

我正在使用SQLDataAdapter从2个DropDownLists中的SQL服务器数据库填充数据。根据第一个下拉列表中选择的内容,相应的数据将填入第二个下拉列表中。它工作正常,但管理员在应用程序一侧删除并且不再在数据库中的数据仍然显示在下拉列表中。

有没有办法可以重置或清除DataAdapter中已有的内容,刷新它然后只显示当前数据?

如果它有帮助,我将如何将数据绑定到下拉列表。首先是在页面加载时调用以填充第一个下拉列表的常规方法,并再次在第一个下拉列表的_SelectedIndexChanged中将相关数据绑定到第二个下拉列表。

 if (!IsPostBack)
        {
            DataBind();
            string query = "select Distinct ClubID, ClubName from Pitch";
            BindDropDownList(DDLClub, query, "ClubName", "ClubID", "Select Club");
            DDLPitches.Enabled = false;
            DDLPitches.Items.Insert(0, new ListItem("Select Pitch", "0"));
        }
 private void BindDropDownList(DropDownList DDL, string query, string text, string value, string defaultText)
    {
        string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(ConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                con.Open();
                DDL.DataSource = cmd.ExecuteReader();
                DDL.DataTextField = text;
                DDL.DataValueField = value;
                DDL.DataBind();
                sda.Dispose();
                con.Close();
            }
        }
        DDL.Items.Insert(0, new ListItem(defaultText, "0"));
    }
 protected void DDLClub_SelectedIndexChanged(object sender, EventArgs e)
    {
        DDLPitches.Enabled = false;
        DDLPitches.Items.Clear();
        DDLPitches.Items.Insert(0, new ListItem("Select Pitch", "0"));
        int ClubID = int.Parse(DDLClub.SelectedItem.Value);
        if (ClubID > 0)
        {
            string query = string.Format("select PitchID, ClubID, ClubName, PitchName from Pitch where ClubID = {0}", ClubID);
            BindDropDownList(DDLPitches, query, "PitchName", "PitchID", "Select Pitch");
            DDLPitches.Enabled = true;
        }
    }

0 个答案:

没有答案