1

我正在尝试动态加载LinkButton以触发回发事件,然后我会处理该事件。

我有Command,CommandNameCommandArgument- 这看起来真的很有用.. 所以我开始搞砸了,但目前无法按要求工作。

链接在动态创建的表中呈现,这是生成它们的代码:

    // The links are stored in Session since I was told that the objects need to remain intact across requests.
    LinkButton GetEditCardLink(string card)
    {
        if (!IsPostBack)
        {
            TW("Creating Link for Card '" + card + "' and Placing in Session.", true);
            LinkButton link = CreateEditLink(card);
            Business.Session.Set<LinkButton>("LinkedCards_EditLink_" + card, link);
        }
        return Business.Session.Get<LinkButton>("LinkedCards_EditLink_" + card);
    }

    // Here the link itself is created, note the ID and Command details are set.
    LinkButton CreateEditLink(string forCard)
    {
        TW("Setting Up Link for Card: " + forCard, true);
        LinkButton rtn = new LinkButton();
        rtn.ID = "Edit_" + forCard;
        rtn.Text = Resources.Header("EditDetails");
        rtn.CommandName = "Edit";
        rtn.CommandArgument = forCard;
        rtn.Command += new CommandEventHandler(RedirectToEdit);
        rtn.Attributes["style"] = "display: block; text-align:center;";
        return rtn;
    }

    // ... And the delegate I want called on PostBack..
    void RedirectToEdit(object sender, CommandEventArgs e)
    {
        TW("RedirectToEdit Called:\r\nName: " + e.CommandName + "\r\nArgument: " + e.CommandArgument);
    }

Trace确认LinkBut​​tons被正确加载,并且只创建一次,所以理论上它们应该没问题,但是当我点击链接时,执行了一个PostBack,但RedirectToEdit没有调用该方法?

感谢所有帮助!:)

笔记

哦,我想我应该提到TW的只是一个实用方法Trace.Write/Warn:)

4

2 回答 2

1

当您创建需要事件处理的控件时,您必须在处理过程中尽早完成,以使事件处理程序连接起来。覆盖您正在创建表的页面的 OnInit 并将表创建代码移到那里。正如@ScarletGarden 建议的那样,您还需要添加控件,无论它是否是 PostBack。我相信在 Page_Load 中执行此操作为时已晚,如果您在其中添加控件,则无法检测到事件。

参考

于 2009-02-05T12:33:51.427 回答
0

这是我的试验,它奏效了:

protected void Page_Load(object sender, EventArgs e)
{
    //if (!IsPostBack)
    //{
        placeHolderAtPage.Controls.Add(CreateEditLink("forCard1"));
    //}
}

LinkButton CreateEditLink(string forCard)
{
    LinkButton rtn = new LinkButton();
    rtn.ID = "Edit_" + forCard;
    rtn.Text = "EditDetails";
    rtn.CommandName = "Edit";
    rtn.CommandArgument = forCard;
    rtn.Command += new CommandEventHandler(RedirectToEdit);
    rtn.Attributes["style"] = "display: block; text-align:center;";
    return rtn;
}

void RedirectToEdit(object sender, CommandEventArgs e)
{
    Response.Write("RedirectToEdit Called:\r\nName: " + e.CommandName + "\r\nArgument: " + e.CommandArgument);
}

如果您取消 IsPostBack 行,RedirectToEdit 将毫无用处。只有绑定代码可以在IsPostBack控制之下。

于 2009-02-05T12:29:51.373 回答