Search code examples
c#asp.netlistviewlistviewitem

ListView string from aspx to codebehind


Hello I have following aspx code and when the button inside ItemTemplate is cliked i need to pass the Item.BookID into code behind and I am unsure how to do it as there can be multiple items in the view. Thank you help would be much appreciated.

<asp:ListView runat="server" ID="UserDetailBooks" DefaultMode="ReadOnly" ItemType="WebApplication1.Models.Borrowed" SelectMethod="GetBorrow" DeleteMethod="ReturnBook">

    <EmptyDataTemplate>
        <h3>No borrowed books!</h3>
    </EmptyDataTemplate>
    <LayoutTemplate>

        <div style="margin-left: auto; margin-right: auto; width: 50%;">
            <h4>Books in possesion:</h4>
            <table style="border-spacing: 2px;">

                <tr id="groupPlaceholder" runat="server">
                </tr>
            </table>
        </div>
    </LayoutTemplate>

    <GroupTemplate>
        <tr>

            <td id="itemPlaceholder" runat="server"></td>
        </tr>

    </GroupTemplate>

    <ItemTemplate>
        <td><asp:Button runat="server" Text="Return" OnClick="ReturnBook" />
            <a href="BookDetail.aspx?BookID=<%#:Item.BookID %>"><%#:Item.BookTitle %></a>      
        </td>
    </ItemTemplate>

</asp:ListView>

Solution

  • You could pass the id in the button attributes?

    <asp:Button runat="server" Text="Return" BookID="<%#:Item.BookID %>" OnClick="ReturnBook" />
    <a href="BookDetail.aspx?BookID=<%#:Item.BookID %>"><%#:Item.BookTitle %></a> 
    
    void ReturnBook(object sender, EventArgs e) {
     Button b = sender;
     string BookId = b.Attributes["BookID"];
    }