ASP.NET - 从数据列表值填充下拉列表
本文关键字:填充 下拉列表 列表 数据 NET ASP | 更新日期: 2023-09-27 18:32:29
我正在为自己开发一个婚礼网站,这样我们就可以让客人从我们的礼物清单中预订物品(这是我们在蜜月时要做的事情(,并在当天给我们一张支票。
我有一个数据列表,它正在从我的 MSSQL 中检索一个表并将其显示在我的 aspx 页面上。此表中存储的值之一是数量。
我想要的是能够使用"数量"字段中的选项数量填充asp:DropDownList,然后单击一个按钮,这会将该项目的X添加到购物车中(购物车运行良好,带有用于添加一个选项的按钮(。我挣扎的地方实际上是让下拉列表填充。我目前的想法是让 C# 函数根据数量在 for 循环中添加新项目。
这是我正在尝试的
.aspx
<asp:DataList ID="DataList2" runat="server" DataKeyField="pKey" DataSourceID="WeddingDatabase">
<ItemTemplate>
<div class="Gift">
<!-- Other fields ignored for purpose of quesion -->
Quantity:
<asp:Label ID="QuantityLabel" runat="server" Text='<%# Eval("Quantity") %>' />
<br />
<asp:DropDownList ID="QuantityDropdown" runat="server" />
<% FillDropdown((int)Eval("Quantity")); %>
<br />
<asp:Button ID="Btn" runat="server" Text="Add to Cart" CommandArgument='<%# Eval("pKey") %>' OnCommand="AddToCart" />
</div>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9EF896_weddingConnectionString %>"
SelectCommand="SELECT * FROM [Giftlist] ORDER BY [Title] ASC"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"></asp:SqlDataSource>
aspx.cs
public void FillDropdown(int inQuantity)
{
DropDownList dropdown = this.FindControl("QuantityDropdown") as DropDownList;
for (int i = 0; i < inQuantity; i++)
{
dropdown.Items.Add(new ListItem("" + (i+1)));
}
}
现在我什至正在努力编译它。虽然我知道我想做什么,但代码在这里占了上风。
任何帮助将不胜感激!
为什么
不配置另一个SqlDataSource
并将其绑定到您的下拉列表中,例如
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9EF896_weddingConnectionString %>"
SelectCommand="SELECT distinct quantity FROM [Giftlist]"></asp:SqlDataSource>
<asp:DropDownList DataValueField="quantity" SelectedValue='<%# Eval("quantity") %>'
ID="QuantityDropdown" runat="server" DataSourceID="SqlDataSource3"
DataTextField="quantity"></asp:DropDownList>
我的解决方案是通过 C# 函数在数据列表中传入该项的数量来设置数据源。
.aspx
<asp:DropDownList ID="QuantityDrop" runat="server" DataSource='<%# FillDropdown((int)Eval("Quantity")) %>' />
C# (aspx.cs(
public ArrayList FillDropdown(int inCount)
{
ArrayList values = new ArrayList();
for (int i = 0; i < inCount; i++)
{
values.Add("" + (i + 1)); // increment i and add.
}
return values;
}