制作下拉列表在ASP.Net由foreach循环 [英] Making drop down list in ASP.Net by foreach loop
本文介绍了制作下拉列表在ASP.Net由foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以在asp.net组件下拉列表下面的语法
we can make dropdown list in asp.net component with below syntax
<asp:DropDownList ID="test" runat="server">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
如果我们希望我们的组合框包含1到1000,有没有办法用foreach循环来填充它,而不是手动添加1000项呢?
if we want our combo box contain 1 to 1000 , is there any way to populate it with foreach loop , rather than manually add 1000 item to it ?
推荐答案
是的,你可以添加 ListItems的
编程方式:
Yes, you can add ListItems
programmatically:
for(int i=1; i<=1000; i++)
{
ListItem item = new ListItem(i.ToString(), i.ToString());
test.Items.Add(item);
}
您也可以使用这个LINQ查询并使用它作为数据源:
You could also use this linq query and use it as DataSource:
var source = Enumerable.Range(1, 1000)
.Select(i => new { Text= i.ToString(), Value=i.ToString() });
test.DataSource = source;
test.DataTextField = "Text";
test.DataValueField = "Value";
test.DataBind();
这篇关于制作下拉列表在ASP.Net由foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文