ASP.NET - 从 DataList 值填充 DropDownList

ASP.NET - Populate DropDownList from DataList value

我正在为自己开发一个婚礼网站,这样我们就可以让我们的客人从我们的礼物清单中预订物品(这是我们将在蜜月期间做的事情)并在当天给我们支票。

我有一个 DataList,它从我的 MSSQL 中检索 table 并将其显示在我的 aspx 页面上。此 table 中存储的值之一是数量。

我想要的是能够使用“数量”字段中的选项数量填充 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# 函数设置 DataSource,传入 Datalist 中该项目的数量。

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;
}