[C#][WebForm]GridView_RowDataBound事件導致分頁錯誤

  • 6670
  • 0
  • C#
  • 2009-12-11

[C#][WebForm]GridView_RowDataBound事件導致分頁錯誤

這天MSN朋友傳來GridView無法實現分頁,本以為他應該是漏了PageIndexChanging事件

但他卻說PageIndexChanging有實作可是分頁碼卻顯示"0",而且Table筆數超過三萬筆

越想越怪怎麼會顯示"0",後來才發現原來是GridView_RowDataBound事件中

漏了判斷控制項資料列導致分頁功能也掛了。

這裡簡單模擬該狀況,同時記錄一下。

 

錯誤畫面

image 

.cs(錯誤代碼,遺漏資料列判斷) 

private void GetData()
        {
            SqlDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString;
            SqlDataSource1.SelectCommand = "select * from Person.Address";               
            GridView1.DataSourceID = SqlDataSource1.ID;
            GridView1.AllowPaging = true;
            GridView1.AllowSorting = true;
            GridView1.PageSize = 15;
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GetData();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {          
            if (e.Row.RowType != DataControlRowType.Header)
            {
                e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
                //當滑鼠停留時更改背景色
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#E8CCFF'");
                //當滑鼠移動後還原背景色
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        } 

正確畫面

 image

HTML

 image

.cs(正確代碼,加上資料列判斷)

private void GetData()
        {
            SqlDataSource1.ConnectionString = ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString;
            SqlDataSource1.SelectCommand = "select * from Person.Address";               
            GridView1.DataSourceID = SqlDataSource1.ID;
            GridView1.AllowPaging = true;
            GridView1.AllowSorting = true;
            GridView1.PageSize = 15;
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GetData();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {          
            if (e.Row.RowType==DataControlRowType.DataRow)
            {
                e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
                //當滑鼠停留時更改背景色
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#E8CCFF'");
                //當滑鼠移動後還原背景色
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        } 

 由於啟用分頁功能後會多一個Pager的Row,當資料列準備繫結至GridView時,因為沒判斷控制項資料列

導致最後一個Row的內容又被修改掉,以至於分頁碼無法正常顯示。