Simo
Simo

Reputation: 67

dynamic dropdownlist in asp.net

I have a page called "product.aspx" which lists all products, but it display 12 items, so I have to create a dropdownlist which has the number of pages, the problem is in this dropdownlist it doesn't work well!

I mean, I put the value autopostback=true and I create the event of indexchange cause I need to get the value selected, but ListBxNbrPG.SelectedItem.Value it always return number 1 which is the the first item in the dropdownlist no matter the number I have selected but always it returns the number 1

  protected void Page_Load(object sender, EventArgs e)
    {
         int nbr = (int)DB.ExecScal("select count(*) from produit");
        nbr = ((nbr % 12) == 0) ? (nbr / 12) : (int)(nbr / 12) + 1; // number of pages

        ListBxNbrPG.Items.Clear(); //initialisation of dropdownlist

        for (int i = 1; i <= nbr; i++)
        {
            ListBxNbrPG.Items.Add(i.ToString());
            ListBxNbrPG.Items[i - 1].Value = i.ToString();
           

        }

        
         if (Request.Params["pg"] != "" )
            {
              label.text=Request.Params["pg"].ToString(); //always it give number 1
            }
      

    }

    protected void ListBxNbrPG_SelectedIndexChanged(object sender, EventArgs e)
    {      
        Response.Redirect("product.aspx?pg="+ListBxNbrPG.SelectedItem.Value.ToString());
        
        /* ListBxNbrPG.SelectedItem.Value.ToString() it return always number 1*/
    }

Upvotes: 0

Views: 107

Answers (2)

user3527145
user3527145

Reputation: 1

Fill your dropdown list in initial get request. Then you can do as many postbacks as you wish by keeping the same data at the time of first request.

if(!IsPostBack)

{

dropdownlist.databind();

}

Upvotes: 0

Rick S
Rick S

Reputation: 6586

Everytime you select an item from your dropdownlist you are posting back to the server and reloading your list. In Page_Load, you need wrap your code inside !Page.IsPostBack.

if (!Page.IsPostBack ) {

    int nbr = (int)DB.ExecScal("select count(*) from produit");
    nbr = ((nbr % 12) == 0) ? (nbr / 12) : (int)(nbr / 12) + 1; // number of pages

    ListBxNbrPG.Items.Clear(); //initialisation of dropdownlist

    for (int i = 1; i <= nbr; i++)
    {
        ListBxNbrPG.Items.Add(i.ToString());
        ListBxNbrPG.Items[i - 1].Value = i.ToString();


    }


     if (Request.Params["pg"] != "" )
     {
        label.text=Request.Params["pg"].ToString(); //always it give number 1
     }

}

Upvotes: 2

Related Questions