How to use linkbutton in repeater using C# with ASP.NET 4.5

前端 未结 1 1873
轮回少年
轮回少年 2020-12-20 23:35

In asp.net I have a table in database containing questions,date of submission and answers.On page load only questions appear.now i want to use any link which on clicking sho

相关标签:
1条回答
  • 2020-12-20 23:48

    I believe you could handle the ItemCommand event of the Repeater.

    Place a LinkButton control for the link that you want the user to click in the Repeater's item template. Set the CommandName property of this to something meaningful, like "ShowAnswers". Also, add a Label or TextBox control into the Repeater's item template, but set their Visible property to false within the aspx markup.

    In the code-behind, within the ItemCommand event handler check if the value of e.CommandName equals your command ("ShowAnswers"). If so, then find the Label or TextBox controls for the answers and date within that Repeater item (accessed via e.Item). When you find them, set their Visible property to true.

    Note: you could take a different approach using AJAX to provide a more seamless experience for the user, but this way is probably simpler to implement initially.

    I think the implementation would look something like this. Disclaimer: I haven't tested this code.

    Code-Behind:

    void Repeater_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "ShowAnswers")
        {
            Control control;
    
            control = e.Item.FindControl("Answers");
            if (control != null)
                control.Visible = true;
    
            control = e.Item.FindControl("Date");
            if (control != null)
                control.Visible = true;
        }
    }
    

    ASPX Markup:

    <asp:Repeater id="Repeater" runat="server" OnItemCommand="Repeater_ItemCommand">
      <ItemTemplate>
        <asp:LinkButton id="ShowAnswers" runat="server" CommandName="ShowAnswers" />
        <asp:Label id="Answers" runat="server" Text='<%# Eval("Answers") %>' Visible="false" />
        <asp:Label id="Date" runat="server" Text='<%# Eval("Date") %>' Visible="false" />
      </ItemTemplate>
    </asp:Repeater>
    
    0 讨论(0)
提交回复
热议问题