c# - 如何在使用 C# 和 ASP.NET 4.5 的中继器中使用链接按钮

标签 c# asp.net repeater asplinkbutton

在 asp.net 中,我在数据库中有一个表,其中包含问题、提交日期和答案。在页面加载时只出现问题。现在我想使用任何链接,单击它会显示表数据中指定的答案和日期,无论是在文本框或标签并再次单击该链接答案再次消失,就像单击时展开和收缩一样。 那么我应该在 C# 中使用什么编码呢?

最佳答案

我相信你可以处理 ItemCommand中继器的事件。

在 Repeater 的项模板中为您希望用户单击的链接放置一个 LinkBut​​ton 控件。将其 CommandName 属性设置为有意义的内容,例如“ShowAnswers”。此外,将 Label 或 TextBox 控件添加到 Repeater 的项目模板中,但在 aspx 标记中将其 Visible 属性设置为 false。

在代码隐藏中,在 ItemCommand 事件处理程序中检查 e.CommandName 的值是否等于您的命令(“ShowAnswers”)。如果是,则在 Repeater 项目中找到答案和日期的 Label 或 TextBox 控件(通过 e.Item 访问)。当您找到它们时,将它们的 Visible 属性设置为 true。

注意:您可以采用使用 AJAX 的不同方法来为用户提供更无缝的体验,但这种方法最初可能更容易实现。

我认为实现看起来像这样。免责声明:我尚未测试此代码。

代码隐藏:

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 标记:

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

关于c# - 如何在使用 C# 和 ASP.NET 4.5 的中继器中使用链接按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14861690/

相关文章:

asp.net - 嵌套中继器错误: Object reference not set to an instance of an object

Python - 冒泡排序

c# - 如何指向存储在项目文件夹中的文件? WPF

c# - 从静态类的静态属性访问 session 值

asp.net - 内容特定的 JavaScript 和母版页

ASP.NET - 检测转发器中的更改值?

c# - 查找子集合包含列表所有元素的行

c# - 奇怪的空字符串连接行为

c# - 当 IsInputKey 设置为真时,为什么会第二次调用 PreviewKeyDown 事件?

javascript - 如何从 ASP.NET 中的复选框调用 javascript 函数?