2010-01-31 54 views
0

我有我我的.aspx頁面上的頁面與下面的標記之一的非常簡單的GridView:的GridView分頁問題

<asp:GridView ID="gvNews" runat="server" AutoGenerateColumns="false" AllowPaging="true" 
      AllowSorting="true" DataKeyNames="NewsID,VersionStamp" OnPageIndexChanging="gvNews_PageIndexChanging" 
      OnRowCreated="gvNews_RowCreated"> 
      <Columns> 
       <asp:BoundField HeaderText="News Title" DataField="NewsTitle" 
        SortExpression="NewsTitle" ReadOnly="true" /> 
       <asp:BoundField HeaderText="News Content" DataField="NewsContent" 
        SortExpression="NewsContent" ReadOnly="true" /> 
       <asp:BoundField HeaderText="Posted Date" DataField="InsertedDate" 
        SortExpression="InsertedDate" ReadOnly="True" /> 
       <asp:BoundField HeaderText="InsertedBy" DataField="InsertedBy" /> 
       <asp:TemplateField> 
        <ItemTemplate> 
         <asp:LinkButton ID="lbEdit" runat="server" Text="Edit" CommandName="Select" /> 
        </ItemTemplate> 
       </asp:TemplateField> 
      </Columns> 
     </asp:GridView> 

下面是我的.cs頁上的代碼:

protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       LoadGrid(); 
      } 
     } 

     private void LoadGrid() 
     { 
      gvNews.DataSource = GetNews(); 
      gvNews.DataBind(); 
     } 


     protected void gvNews_PageIndexChanging(object sender, GridViewPageEventArgs e) 
     { 

     } 

     protected void gvNews_RowCreated(object sender, GridViewRowEventArgs e) 
     { 
      e.Row.Cells[3].Visible = false; 
     } 

在RowCreated事件我試圖隱藏GridView中的InsertedBy列。當AllowPaging設置爲flase時,此代碼正常工作。但是,當AllowPaging設置爲true時,RowCreated事件處理函數中出現以下錯誤:

指定的參數超出了有效值的範圍。 參數名稱:index

這種行爲的原因是什麼?

回答

0

你需要編寫的代碼是這樣的:

protected void gvNews_RowCreated(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     e.Row.Cells[3].Visible = false; 
    } 
} 

有了一個GridView有不同類型的可能會產生,他們將有細胞的不同數量的行,但RowCreated事件將觸發對所有行,所以在這種情況下,您需要將邏輯限制爲僅限數據行。

+0

謝謝,這工作完美。我們還需要檢查標題行,以便標題和數據行不可見: if(e.RowTypeRowType == DataControlRowType.DataRow || e.RowType == DataControlRowType.Header) {e.Row.Cells [3] .Visible = false; } – Kumar 2010-01-31 18:49:26

0

從RowCreated事件中發佈的硬編碼值3看起來就像是問題所在。在頁面上啓用跟蹤並查看您獲得的內容。順便說一下,pager next-> prev鏈接也會導致回發,並且在PageLoad中,如果它不是一個回傳,那麼當你嘗試去下一頁並且創建的行被觸發時,你只會加載網格。