levi
levi

Reputation: 3511

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; }
    }

Upvotes: 1

Views: 1270

Answers (2)

levi
levi

Reputation: 3511

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();

Upvotes: 1

Girish Sakhare
Girish Sakhare

Reputation: 11

One quick thing, on first load as per your code your current page index will be returned as 0. Then on subsiquent page clicks like if you click on Page 2, the current page index returned will be 2, however if the page index starts with 0 then 2 means 3rd page rather than second page. So i guess while setting the current page you should do as follows:

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

Upvotes: 0

Related Questions