2013-03-11 162 views
0

我在3個不同的頁面中有3個GridView控件。他們以前工作得很好。 突然我得到這個錯誤信息:Gridview:索引超出範圍

無效的回發或回調參數。事件驗證使用<pages enableeventvalidation="true" />

所以我試着把<@pages enableeventvalidation="false" />在頁面中。它仍然沒有工作。 我從頁面刪除了這個命令。然後當單擊gridview中所有girdview控件的按鈕時,另一條消息顯示「索引超出範圍」。

int id = Convert.ToInt32(myGridView.DataKeys[e.RowIndex].Value) 

它看起來像在GridView找不到datakey(e.rowIndex的價值是OK),的DataKeyNames已設置。

protected void gvItemCategory_RowDeleting(object sender, GridViewDeleteEventArgs e) { 

    int categoryId = Convert.ToInt32(gvItemCategory.DataKeys[e.RowIndex].Value); 

    CollectionCategory category = new CollectionCategory(); 
    category.CategoryId = categoryId; 
    category.Delete(); 
    ItemCateogryShowData(); 
} 

HTML:

<asp:GridView ID="gvItemCategory" runat="server" AutoGenerateColumns="False" 
OnRowCancelingEdit="gvItemCategory_RowCancelingEdit" 
    OnRowDeleting="gvItemCategory_RowDeleting" OnRowEditing="gvItemCategory_RowEditing" 
    DataKeyNames="CategoryId" OnRowUpdating="gvItemCategory_RowUpdating"> 
    <Columns> 
     <asp:TemplateField HeaderText="CateogoryName"> 
      <ItemTemplate> 
       <asp:Label ID="lblItemCategoryName" runat="server" Text='<%#Eval("CategoryName") %>'></asp:Label> 
      </ItemTemplate> 
      <EditItemTemplate> 
       <asp:TextBox ID="tbItemCateogryName" runat="server" Text='<%#Eval("CategoryName") %>'></asp:TextBox> 
      </EditItemTemplate> 
     </asp:TemplateField> 
     <asp:CommandField ShowEditButton="True" ButtonType="Button" /> 
     <asp:CommandField ShowDeleteButton="True" /> 
    </Columns> 
    </asp:GridView> 
+0

你是否通過javascript操作任何東西(例如,添加項目到下拉菜單)?你在回發數據綁定網格?然後索引變爲-1,這將超出範圍。 – 2013-03-11 11:13:26

+0

當您嘗試enableeventValidation =「false」時會發生什麼。 – coder 2013-03-11 11:26:16

+0

在頁面中放入enableeventValidation =「false」後,「無效回傳或回調參數」錯誤消息消失,我可以看到頁面內容。但gridview按鈕有問題 – yilee 2013-03-11 11:37:38

回答

0

嘗試在頁面加載!ispostback方法綁定你的GridView ..

If(!isPostback) 
{ 
//your code here 
} 

試試這個

int categoryId = Convert.ToInt32(gvItemCategory.DataKeys[e.RowIndex].Value.Tostring()); 

注意:同樣使用EnableeventValidation="false"

+0

我試過了,它不起作用。 – yilee 2013-03-11 11:38:08

+0

@ user2156481你得到的錯誤是什麼。 – coder 2013-03-11 11:39:33

+0

指數超出範圍。必須是非負數且小於集合的大小。字符串id = myGridView.DataKeys [row.rowIndex] .value.ToString() – yilee 2013-03-11 11:46:14