简体   繁体   中英

asp.net insert new dropdown list with C# code

I am developing a website which retrieves data from a database but im new to web developing.

I use gridviews,dropdown lists and others, to show data but there is a page where the website user will set how many specific dropdown lists will need to do his work.

To be more specific the user will choose products and each products' quantity but i don't know how many products the user will need. If the user wants to enter x number of products, i want to create x number of drowdown lists(in different rows), so that he could select x number of products and their quantities.

eg User A wants to select 2 tomatoes,3 potatoes and 5 watermelons. He will type 3(for number of products) in a textbox and then 3 rows will appear with 2 dropdown lists each, and user will select

tomatoes 2

potatoes 3

watermelons 5

add new line->>>this is another thing i want to create

Any ideas??

In the codebehind, specifically during the Page_Load event, you'll want to determine how many dropdowns are needed, and then create them on the fly. There are quite a few examples that would result from a google search, but a quick example would look like:

int countNeeded = 15; //or whatever your code tells you is the right amount

for (int x = 0; x < 15; x++)
{
    mainContent.Controls.Add(new DropDownList()); 
    //mainContent would be a control on the page that you want to host your controls.
} 

You can create the controls you need in code-behind. The things you should consider when doing so:

  • create the controls in Page_Init or Page_Load events
  • recreate the controls on each page load when you want them to appear (including postbacks)
  • you can put each dropdown in separate row of a table if you want them to appear in separate lines OR you can put LiteralControl between them

Some sample code:

protected void Page_Load(object sender, EventArgs e)
{
    //read how many DropDownList controls are needed
    int ddlCount = txtDropDownList.Text;

    for (int i = 0; i < ddlCount; ++i)
    {
        if (i > 0)
        {
            //add a page break between previous DropDownList and the current one
            this.Controls.Add(LiteralControl("<br />"));
        }

        //add a DropDownList with ID productDdl and an appropriate number
        this.Controls.pageContent.Add(new DropDownList() { ID = String.Format("productDdl{0}", i) });
    }
}

I haven't tested this code, so if you find any issues, let me know and I'll try to correct them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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