下拉列表数据绑定功能刷新列表,还可以添加已有的数据



我有一个将值插入DropDownList的表单。当我说

   DropDownList.DataBind() ;

在save函数中,它附加了我刚刚键入的新字段以及DropDownList上所有其他已经存在的选项。关于如何阻止这种情况,有什么建议吗?DropDownList由单独的数据源填充。

protected void BtnNewTugSave_Click(object sender, EventArgs e)
    {
        try
        {
            //saving stuff
            con.Close();
            DropDownListX.DataBind();

        }
    catch (Exception ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }
    }

    <asp:DropDownList ID="DropDownList" runat="server" DataSourceID="SqlDataSourceT"
                                            DataTextField="T_Name" DataValueField="T_ID" AutoPostBack="True" AppendDataBoundItems="True"
                                            OnSelectedIndexChanged="ShowNewRateBtn">
                                            <asp:ListItem Value="0" Text="&lt;Select&gt;" Enabled="True" Selected="False"></asp:ListItem>
                                        </asp:DropDownList>
     <asp:Button ID="NewTug" runat="server" Text="New Tug" OnClick="NewTug_Click" CausesValidation="False" />
                                        <asp:SqlDataSource ID="SqlDataSourceT" runat="server" ConnectionString="<%$ ConnectionStrings X %>"
                                            SelectCommand="SELECT [A, [B] FROM [C]"></asp:SqlDataSource>

在检索数据之前,您应该编写

try
{
    DropDownList.Items.Clear();
    //saving stuff
    DropDownList.DataBind();
}

使用DropDownList.Items.Clear();在您获得新数据并提供下拉列表之前,您的下拉列表中的项目将被删除。

最新更新