动态加载ListButton和PostBack事件

时间:2009-02-05 12:14:18

标签: asp.net dynamic controls postback

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

我遇到了CommandCommandNameCommandArgument - 这看起来很有用..所以我开始搞乱这个,但目前无法按照预期的方式工作。

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

    // 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的实用方法:)

2 个答案:

答案 0 :(得分:1)

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

Reference

答案 1 :(得分: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 控制下。