从GridView中删除行时出错

时间:2011-08-29 07:19:46

标签: c# asp.net

我的ASPX代码是:

<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" 
                                    AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting" AutoGenerateDeleteButton="true">
        <Columns>


        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
        <asp:TemplateField HeaderText="Column Name">
            <ItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>

     <%-- <asp:TemplateField HeaderText="Header 2">
            <ItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>--%>
        <asp:TemplateField HeaderText="Data Type">
            <ItemTemplate>
                  <asp:DropDownList ID="ddldatatype" runat="server">
                  <asp:ListItem>varchar</asp:ListItem>
                  <asp:ListItem>int</asp:ListItem>
                  <asp:ListItem>numeric</asp:ListItem>
                  <asp:ListItem>uniqueidentifier</asp:ListItem>
                  <asp:ListItem>char</asp:ListItem>
                  </asp:DropDownList>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
            <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
             <asp:Button ID="ButtonDel" runat="server" Text="Delete Row" OnClick="ButtonDel_Click" />
             <input type="hidden" runat="server" value="0" id="hiddencount" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkdelete" runat="server" >Delete</asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        </Columns>
</asp:gridview>

我的C#代码是:

 protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
     {

         Gridview1.DeleteRow((int)Gridview1.DataKeys[e.RowIndex].Value);
         Gridview1.DataBind();


     }
 if (!IsPostBack)
        {
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }

我收到错误:

  

指数超出范围。必须是非负数且小于   集合。参数名称:index

1 个答案:

答案 0 :(得分:2)

问题是以下几行:

 Gridview1.DeleteRow((int)Gridview1.DataKeys[e.RowIndex].Value);

并在那里

Gridview1.DataKeys[e.RowIndex]

这不起作用,只需查看DataKeys - 属性和DeleteRow - 方法 我猜你想做什么

Gridview1.DeleteRow(e.RowIndex)

但即使在这里你也应该查看索引!