如何访问内部数据列表中的按钮?

How can access Button in Inner DataList?

评论DataList(外部)和回复DataList(内部)。

而在内部 DataList 中,有一个 LinkButtonTextBox 获取文本。

如何访问 LinkButtonAdd 事件?

.aspx代码

<asp:DataList ID="dlComments" runat="server">
    <asp:DataList ID="dlReplies" runat="server">
        <asp:TextBox ID="txtReply" TextMode="MultiLine" Rows="3" Width="100%" runat="server"></asp:TextBox>
        <asp:LinkButton ID="lbEdit" CommandName="Add" runat="server">Edit</asp:LinkButton>
    </asp:DataList>
</asp:DataList>

在您的链接按钮上添加 commandName="click"

 private void DataList1_ItemCreated(object sender, System.Web.UI.WebControls.DataListItemEventArgs e) {
        if ((e.Item.ItemType == ListItemType.AlternatingItem) 
                    || (e.Item.ItemType == ListItemType.Item)) {
            DataList dtl2 = (DataList)(e.Item.FindControl("dlReplies"));
            dtl2.ItemCommand += new System.EventHandler(this.dtl2_ItemCommand);
        }
    }

    protected void dtl2_ItemCommand(object sender, System.Web.UI.WebControls.DataListCommandEventArgs e) {
        if (e.CommandName == "click") {
            // 'do what you want here
        }
    }

您可以将 OnItemCommand 添加到嵌套的 DataList。

<asp:DataList ID="dlReplies" runat="server" OnItemCommand="dlReplies_ItemCommand">

然后在后面的代码中

protected void dlReplies_ItemCommand(object source, DataListCommandEventArgs e)
{
    //check for the correct commandname
    if (e.CommandName == "Add")
    {
        //use findcontrol to find the textbox and cast it back to one
        TextBox tb = e.Item.FindControl("txtReply") as TextBox;

        Label1.Text = tb.Text;
    }
}