2

I would like to make a DropDownList inside a panel. This is my code from the codebehind file. But if I execute it, it always says: "in DropdownList it is not allowed to make multiple selections." Do I have to do something with the autopostback? So the error comes when I want to select something else than than "All".

DropDownList1.DataTextField = "Kanal";
DropDownList1.DataValueField = "Kanal";
DropDownList1.AppendDataBoundItems = true;
ListItem limDefault = new ListItem();

limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";


            DropDownList1.Items.Add(limDefault);

Then this is my ASP.NET code:

<asp:Panel ID="Panel1" runat="server"> 
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CR_SQL %>" SelectCommand="Select * from table" >
    </asp:SqlDataSource>
    <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"  AutoPostBack="True">
    </asp:DropDownList>
</asp:Panel>
Konamiman
  • 49,681
  • 17
  • 108
  • 138
aha364636
  • 365
  • 5
  • 23

1 Answers1

4

I guess you execute the first snippet on every postback which adds the default item every time. Do that only at the first time the page loads, therefore use Page.IsPostBack to check that:

if(!IsPostBack)
{
    ListItem limDefault = new ListItem();
    limDefault.Selected = true;
    limDefault.Text = "All";
    limDefault.Value = "-1";
    DropDownList1.Items.Add(limDefault);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • @ So, if I set AutoPostback to true, I always need a if(!IsPostBack)? – aha364636 Jul 06 '15 at 10:08
  • 1
    @aha364636: yes, but even without `AutoPostBack=true` since also other controls could postback. If you have enabled `ViewState` all databinding stuff belongs into a `if(!isPostBack){...}` since you don't want/need to execute it multiple times. Only if the datasource changes, for example if you want to show a different order, filter the records or use paging then you have to reload data. – Tim Schmelter Jul 06 '15 at 10:15