[英]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. 我正在开发一个从数据库检索数据的网站,但对于Web开发来说是新手。
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. 我使用gridviews,下拉列表等来显示数据,但是网站用户可以在其中设置一个页面来设置多少特定的下拉列表来完成工作。
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.
如果用户要输入x数量的产品,我想创建x数量的下拉列表(在不同的行中),以便他可以选择x数量的产品及其数量。
eg User A wants to select 2 tomatoes,3 potatoes and 5 watermelons. 例如,用户A要选择2个西红柿,3个土豆和5个西瓜。 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
他将在文本框中键入3(代表产品数量),然后将显示3行,每个行带有2个下拉列表,用户将选择
tomatoes 2 西红柿2
potatoes 3 土豆3
watermelons 5 西瓜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. 在后面的代码中,特别是在
Page_Load
事件期间,您将需要确定需要多少个下拉列表,然后即时创建它们。 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:
这样做时应考虑的事项:
Page_Init
or Page_Load
events Page_Init
或Page_Load
事件中创建控件 LiteralControl
between them LiteralControl
放在它们之间 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. 我尚未测试此代码,因此,如果您发现任何问题,请告诉我们,我将尝试纠正它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.