Search code examples
asp.netbuttonnestedrepeater

How to access a button inside a nested repeater in ASP.net?


I have been trying to understand what is happening and I have searched the web to no avail.

How do I access my buttons that are inside of a nested repeater? I have spent so many hours researching/experimenting and I do not understand what is going on.

HTML Markup:

<asp:Repeater runat="server" ID="repQuestionTopics">
    ....
    <asp:Repeater ID="repQA" runat="server">
        ....
        <strong>Was this article helpful?</strong>&nbsp; 
        <button class="button tiny secondary radius" runat="server" 
              CommandName="voteYes" id="btnVoteHelpfulYes">Yes</button> 
        <button class="button tiny secondary radius" runat="server" 
              CommandName="voteNo" ID="btnVoteHelpfulNo">No</button>
    </asp:Repeater>
</asp:Repeater>

Code-Behind:

//Handles repQuestionTopics.ItemCommand
Public Sub repTopics_ItemCommand(Sender As Object, e As RepeaterCommandEventArgs)
    If e.CommandName = "voteYes" Then
        ....
    End If
End Sub

How do I gain access to repQA? For some reason my code-behind will not let me write the function Handles repQA.ItemCommand - why? I have tried to directly input the function on the asp side by using something like (adding OnClick):

<button class="button tiny secondary radius" runat="server" OnClick="repTopics_ItemCommand"
        CommandName="voteYes" id="btnVoteHelpfulYes">Yes</button> 

When the button voteYes is clicked I want to be able to go to the database and update the counter so I can keep track of how many up votes and down votes there are for that answer to the question.

No matter what change I implement to try and get it to work when I click the button the page refreshes and that is it - nothing else.


Solution

  • HTML Markup: You have to add OnItemCommand event to your inner Repeater repAQ:

    <asp:Repeater ID="repQA" runat="server" OnItemCommand="repQA_ItemCommand">
    

    Code-Behind:

    VB.Net:

    Public Sub repQA_ItemCommand(Sender As Object, e As RepeaterCommandEventArgs)
        // check for right name of command
        If e.CommandName = "voteYes" Then
            ....
        End If
    End Sub
    

    ASP.Net:

    protected void repQA_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        // check for right name of command
        if(e.CommandName == "voteYes")
        {
            ....
        }
    }