2012-12-07 104 views
1

嗨我試圖重新綁定數據到DataList得到它的數據從SqlDataSource但我不斷收到重複的項目。這裏是我的代碼:DropDownList重複項目

<asp:SqlDataSource ID="CategoryDataSource" runat="server" 
    ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True" 
    ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryName] FROM [forum_categories]"> 
</asp:SqlDataSource> 

protected void Button6_Click(object sender , EventArgs e) 
{ 
    string categoryToCreate = CreateCategory.Text; 

    if(categoryToCreate != string.Empty) 
    { 
     CategoryCreateName.Visible = false; 
     DataAccess.insertDataItem(categoryToCreate); 
     CategoryList.DataBind(); 
    } 
    else 
    { 
     CategoryCreateName.Visible = true; 
    } 
} 

insertDataItem插入一個新的類別到數據庫中。

如何更新DropDownList中的項目,以免重複項目?

+1

您可能會檢查你是否有'AppendDataBoundItems'屬性設置爲True。這將導致每個連續的DataBind將項目添加到DropDownList,而不是先清除它。 –

回答

1

試試這個:

protected void Button6_Click(object sender , EventArgs e) 
{ 
    string categoryToCreate = CreateCategory.Text; 

    if(categoryToCreate != string.Empty) 
    { 
     CategoryCreateName.Visible = false; 
     DataAccess.insertDataItem(categoryToCreate); 
     CategoryList.Items.Clear(); 
     CategoryList.DataBind(); 
    }else 
    { 
     CategoryCreateName.Visible = true; 
    } 
}