[ASP.NET] [GridView] 上一頁、下一頁、第一頁、最後一頁

[ASP.NET] [C#] [GridView] 上一頁、下一頁、第一頁、最後一頁

Gridview 上一頁、下一頁、第一頁、最後一頁

新增 OnRowCreated 事件 ,在事件裡的PAGER控制項加入程式

protected void Gridview_OnRowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Pager)
    { 
        //新增LinkButton 
        Label label_Index = new Label();
        LinkButton Button_First = new LinkButton();
        LinkButton Button_Last = new LinkButton();
        LinkButton Button_Next = new LinkButton();
        LinkButton Button_Previous = new LinkButton();

        //第一頁
        Button_First.Text = "第一頁";
        Button_First.CommandName = "first";
        Button_First.ForeColor = Color.Blue;
        Button_First.Click += new EventHandler(PageButtonClick);

        //上一頁
        Button_Previous.Text = "上一頁";
        Button_Previous.CommandName = "previous";
        Button_Previous.ForeColor = Color.Blue;
        Button_Previous.Click += new EventHandler(PageButtonClick);

        //下一頁
        Button_Next.Text = "下一頁";
        Button_Next.CommandName = "next";
        Button_Next.ForeColor = Color.Blue;
        Button_Next.Click += new EventHandler(PageButtonClick);

        //最後一頁
        Button_Last.Text = "最後一頁";
        Button_Last.CommandName = "last";
        Button_Last.ForeColor = Color.Blue;
        Button_Last.Click += new EventHandler(PageButtonClick);


        e.Row.Controls[0].Controls[0].Controls[0].Controls[0].Controls.AddAt(0, (Button_First));
        e.Row.Controls[0].Controls[0].Controls[0].Controls[0].Controls.AddAt(1, (Button_Previous));

        int controlTmp = e.Row.Controls[0].Controls[0].Controls[0].Controls.Count - 1;
        e.Row.Controls[0].Controls[0].Controls[0].Controls[controlTmp].Controls.Add(Button_Next);
        e.Row.Controls[0].Controls[0].Controls[0].Controls[controlTmp].Controls.Add(Button_Last);
    }
}

接著加入click事件

protected void PageButtonClick(object sender, EventArgs e)
{
    LinkButton clickedButton = ((LinkButton)sender);
    
    //第一頁
    if (clickedButton.CommandName == "first")
    {
        Gridview.PageIndex = 0;  
    }

    //上一頁
    else if (clickedButton.CommandName == "previous")
    {
        if (Gridview.PageIndex >= 1)
        {
            Gridview.PageIndex -= 1;
        }
    }

    //下一頁
    else if (clickedButton.CommandName == "next")
    {
        if (Gridview.PageIndex < Gridview.PageCount - 1)
        {
            Gridview.PageIndex += 1;
        }
    }
  
    //最後一頁
    else if (clickedButton.CommandName == "last")
    {
        Gridview.PageIndex = Gridview.PageCount - 1; 
    }
    LoadData();
}

 

 END 

回目錄