Search code examples
c#asp.neteventsgridviewpagertemplate

Dynamic LinkButton on GridView PagerTemplate not firing event


I am doing a custom Pager Template for a gridview & trying to get something like: < 1 2 3 4 >

I am having problems clicking on the numbers...

Inside the PagerTemplate i have a Placeholder named "phLinks" that is being filled on the DataBound Event like this:

protected void DataBound(object sender, EventArgs e)
    {
        if (grid.PageCount > 1)
        {
            for (int i = 0; i < grid.PageCount; i++)
            {
                phLinks.Controls.Add(new LiteralControl("<li>"));
                LinkButton lb = new LinkButton { Text = (i + 1).ToString(), Enabled = grid.PageIndex != i, CommandArgument = i.ToString() };

                lb.Command += new CommandEventHandler(lb_Command);
                lb.CommandName = "Button";

                //lb.Click += new EventHandler(lb_Click);

                phLinks.Controls.Add(lb);
                phLinks.Controls.Add(new LiteralControl("</li>"));
            }
        }
    }

Please note that I have tried first the Click Event and then the Command Event, in both cases i get a post back but the event is not triggered...

What am i missing here?


Solution

  • Either bind your GridView on every postback :

    protected void Page_Load(object sender, EventArgs e)
        {
           MyGridView.DataBind();
    
        }
    

    OR turn off ViewState for your GridView::

    <asp:GridView ID="MyGridView" EnableViewState="false" ... />.