Jinjinov
Jinjinov

Reputation: 2683

asp.net button in ITemplate doesn't fire Repeater ItemCommand event

i am a complete asp.net noob and the solution could be something very simple.

i have found, read and tried many answers to questions very similar to my question, but nothing works. i hope to find some help here.

this works perfectly with no problem:

    <asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
        <ItemTemplate>
            <asp:Button ID="Button1" runat="server" Text='<%# (Container.DataItem as Choice).description %>' CommandName="Choice" CommandArgument='<%# (Container.DataItem as Choice).id %>'/>
            <br />
        </ItemTemplate>
    </asp:Repeater>

code behind:

void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        List<Choice> choiceList = new List<Choice>();
        // ... code to fill the list ...
        Repeater1.DataSource = choiceList;
        Repeater1.DataBind();
    }
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    int idx = int.Parse( e.CommandArgument.ToString() );
    // this function is called
}

but if i use ITemplate it doesn't work:

    <asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
    </asp:Repeater>

code behind:

public class MyButtonTemplate : System.Web.UI.ITemplate
{
    public void InstantiateIn(System.Web.UI.Control container)
    {
        Button button = new Button();
        button.CommandName = "choice";
        button.DataBinding += new EventHandler(Button_DataBinding);
        container.Controls.Add(button);
        container.Controls.Add(new LiteralControl("<br />"));
    }
}
static void Button_DataBinding(object sender, System.EventArgs e)
{
    Button button = (Button)sender;
    RepeaterItem repeaterItem = (RepeaterItem)button.NamingContainer;
    button.ID = "button" + (repeaterItem.DataItem as Choice).id.ToString();
    button.CommandArgument = (repeaterItem.DataItem as Choice).id.ToString();
    button.Text = (repeaterItem.DataItem as Choice).description;
}
void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        List<Choice> choiceList = new List<Choice>();
        // ... code to fill the list ...
        Repeater1.ItemTemplate = new MyButtonTemplate();
        Repeater1.DataSource = choiceList;
        Repeater1.DataBind();
    }
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    int idx = int.Parse( e.CommandArgument.ToString() );
    // this function is NOT called
}

the buttons are displayed, but the event is not fired.

i have already tried saving a delegate in MyButtonTemplate and assigning the button click event - it does not work.

thank you!

Upvotes: 1

Views: 290

Answers (0)

Related Questions