如何从ListView检索Label中的选定文本?

时间:2019-04-13 09:05:36

标签: c# asp.net listview label

这是我在ListView中产品的前端代码。

<div class="col-md-3">
    <div class="card shadow">
        <div class="inner">
            <div class="title">
                <asp:Label ID="lblprodId" runat="server" Text='<%# Eval("flavourID") %>' Style="display: normal"></asp:Label>

                <h3><%# Eval("flavourName") %></h3>
            </div>
            <img class="prodImg" src="pizza/<%# Eval("flavourImg") %>" alt="Card image cap">
            <center><div class="btn"><div><asp:Button ID="btnShowOrder" runat="server" Text="Order This" CssClass="button" OnClick="btnShowOrder_Click"/></div></div></center>
        </div>
    </div>
</div>

这是我的.cs文件。

protected void btnShowOrder_Click(object sender, EventArgs e)
{
    foreach (ListViewItem item in prodList.Items)
    {
        int index = 0;
        Label lblprodId = prodList.Items[index].FindControl("lblprodId") as Label;
        Session["prodID"] = lblprodId.Text.ToString();
    }
    //Session["prodID"] = lblprodId.Text;
}

现在,我只能检索第一项的产品ID。即使我点击其他产品,购物车中显示的ID还是第一个产品ID

1 个答案:

答案 0 :(得分:0)

您不需要foreach循环。您可以使用NamingContainer来获取正确的值。

protected void btnShowOrder_Click(object sender, EventArgs e)
{
    //cast the sender back to a button
    Button btn = sender as Button;

    //get the current item from the listview namingcontainer
    ListViewItem item = btn.NamingContainer as ListViewItem;

    //use findcontrol to locate the label in that item
    Label lbl = item.FindControl("lblprodId") as Label;

    //show result in label outside listview
    Label1.Text = lbl.Text;
}

ASPX

<asp:ListView ID="ListView1" runat="server">
    <ItemTemplate>

        <asp:Label ID="lblprodId" runat="server" Text='<%# Eval("flavourID") %>'></asp:Label>

        <asp:Button ID="btnShowOrder" runat="server" Text="Button" OnClick="btnShowOrder_Click"/>

    </ItemTemplate>
</asp:ListView>