ASP.Net: why is my button's click/command events not binding/firing in a repeater?

后端 未结 5 1701
北海茫月
北海茫月 2020-12-09 12:31

Here\'s the code from the ascx that has the repeater:


    

A sub-he

相关标签:
5条回答
  • 2020-12-09 13:12

    You need to handle the ItemCommand event on your Repeater. Here's an example.

    Then, your button clicks will be handled by the ListOfEmails_ItemCommand method. I don't think wiring up the Click or Command event (of the button) in ItemDataBound will work.

    0 讨论(0)
  • 2020-12-09 13:12

    If you're planning to use ItemCommand event, make sure you register to ItemCommand event in Page_Init not in Page_Load.

    protected void Page_Init(object sender, EventArgs e)
    {
        // rptr is your repeater's name
        rptr.ItemCommand += new RepeaterCommandEventHandler(rptr_ItemCommand);
    }
    

    I am not sure why it wasn't working for me with this event registered in Page_Load but moving it to Page_Init helped.

    0 讨论(0)
  • 2020-12-09 13:12

    You know what's frustrating about this?

    If you specify an OnClick in that asp:Button tag, the build will verify that the named method exists in the codebehind class, and report an error if it doesn't... even though that method will never get called.

    0 讨论(0)
  • 2020-12-09 13:17

    Here's an experiment for you to try:

    Set a breakpoint on ListOfEmails_ItemDataBound and see if it's being called for postbacks.

    0 讨论(0)
  • 2020-12-09 13:25

    Controls nested inside of Repeaters do not intercept events. Instead you need to bind to the Repeater.ItemCommand Event.

    ItemCommand contains RepeaterCommandEventArgs which has two important fields:

    • CommandName
    • CommandArgument

    So, a trivial example:

    void rptr_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            // Stuff to databind
            Button myButton = (Button)e.Item.FindControl("myButton");
    
            myButton.CommandName = "Add";
            myButton.CommandArgument = "Some Identifying Argument";
        }
    }
    
    void rptr_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Add")
        {
            // Do your event
        }
    }
    
    0 讨论(0)
提交回复
热议问题