Search code examples
c#asp.netpage-refreshrunatserverispostback

Drop Down List that is created by code behind refresh the page


I am trying to create a list of DDL using code behind as you can see here :

public List<DropDownList> ddll = new List<DropDownList>();
for (int i = 0; i < 15; i++)
{
    DropDownList ansList = new DropDownList();
    ansList.AutoPostBack = false;
    ansList.DataSource = values1;
    ansList.DataBind();
    ddll.Add(ansList);
 }

As you can see i set the autopostback attribute on false .But it doesn't work any my pages are refreshed when the user changes the selectedindex.

I added DDL using this :

Span1.Controls.Add(ddll[0]);
Span2.Controls.Add(ddll[1]);
Span3.Controls.Add(ddll[2]);
Span4.Controls.Add(ddll[3]);
Span5.Controls.Add(ddll[4]);
Span6.Controls.Add(ddll[5]);
Span7.Controls.Add(ddll[6]);
Span8.Controls.Add(ddll[7]);
Span9.Controls.Add(ddll[8]);
Span10.Controls.Add(ddll[9]);
Span11.Controls.Add(ddll[10]);
Span12.Controls.Add(ddll[11]);
Span13.Controls.Add(ddll[12]);
Span14.Controls.Add(ddll[13]);
Span15.Controls.Add(ddll[14]);

In html code i have this :

<span style="color:#ea0000;padding:0 10px;" id="Span6" runat="server"></span>

Solution

  • You first set AutoPostBack to false and later to true right after two statements. The false is overwritten by true and it should do postback now when the selected index is changed.

    ansList.AutoPostBack = false;
       //...    
    
    ansList.AutoPostBack = true;
    

    Edit You can also use loop to add the list in the spans using FindControl(string id) to get the spans by id.

    for(int i=0; i < 15; i++)
       this.FindControl("Span"+i).Add(ddll[i]);