简体   繁体   English

asp.net中的动态下拉列表

[英]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!我有一个名为“product.aspx”的页面,它列出了所有产品,但它显示了 12 个项目,所以我必须创建一个包含页数的下拉列表,问题是在这个下拉列表中它不能正常工作!

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我的意思是,我把值 autopostback=true 并创建了 indexchange 事件,因为我需要选择值,但是 ListBxNbrPG.SelectedItem.Value 它总是返回数字 1,这是下拉列表中的第一项,无论数字如何我已经选择但总是返回数字 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*/
    }

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 .在 Page_Load 中,您需要将代码包装在!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
     }

}

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)如果(!IsPostBack)

{ {

dropdownlist.databind();

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM