Search code examples
c#asp.net.netdynamicpagination

Dynamically Added LinkButtons Don't Fire OnClick Event


I need paging on my web page. I use PagedDataSource for it. but I need pages to enumerated on the .aspx , So I add LinkButtons dynamically to PlaceHolder and Write one Eventhandler for all of them. It shows and works fine. on the first click Eventhandler is fired. on the second it doesn't fire. on the third it is. and so on... Any Idea?

    protected void Page_Load(object sender, EventArgs e)
    {
        bindrepeater();
    }


    private void bindrepeater()
    {
        var service = new Service();
        var coll = service.GetPeople();

        PagedDataSource Pds1 = new PagedDataSource();
        Pds1.DataSource = coll;
        Pds1.AllowPaging = true;
        Pds1.PageSize = 10;
        Pds1.CurrentPageIndex = CurrentPage;

        Repeater1.DataSource = Pds1;
        Repeater1.DataBind();

        var count = (coll.Count / 10) + 1;
        pages.Controls.Clear();
        for (int i = 1; i < count; i++)
        {
            var lb = new LinkButton() { Text = i.ToString(), CssClass = "hrefia" };
            lb.Click += new EventHandler(lb_Click);
            pages.Controls.Add(lb);
        }
    }

    protected void lb_Click(object sender, EventArgs e)
    {
        var lb = (LinkButton)sender;
        CurrentPage = int.Parse(lb.Text);
        bindrepeater();
    }

    public int CurrentPage
    {
        get
        {
            object s1 = this.ViewState["CurrentPage"];
            if (s1 == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(s1);
            }
        }
        set { this.ViewState["CurrentPage"] = value; }
    }

Solution

  • It was needed to give ID to all of the linkbuttons. @Hassan Boutougha ansered me in comments...

    var lb = new LinkButton() { Text = i.ToString(), CssClass = "hrefia" };
    lb = "btnId" + i.ToString();