前台:<asp:TemplateField HeaderText="数量">
                    <ItemTemplate>
                        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:ImageButton ID="sub" runat="server" CommandName="sub" CommandArgument='<%#Eval("ID") %>'
                                    CausesValidation="false" CssClass="as" ImageUrl="~/Images/sub.gif" />
                                <asp:TextBox ID="count" runat="server" onchange="check(this)" Text='<%#Eval("数量") %>'></asp:TextBox>
                                <asp:ImageButton CssClass="as" ID="add" CommandName="add" runat="server" CausesValidation="false"
                                    ImageUrl="~/Images/add.gif" /></ContentTemplate>
                        </asp:UpdatePanel>
                    </ItemTemplate>
                </asp:TemplateField>后台:在GridView1_RowCreated事件中
if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton add = (ImageButton)GridView1.Rows[e.Row.RowIndex].FindControl("add");
            add.CommandArgument = e.Row.RowIndex.ToString();
            ImageButton sub = (ImageButton)GridView1.Rows[e.Row.RowIndex].FindControl("sub");
            sub.CommandArgument = e.Row.RowIndex.ToString();
        }
运行出现错误
索引超出范围。必须为非负值并小于集合大小。
参数名: index 调试了一下,发现是控件为null

解决方案 »

  1.   

    试在OnRowDataBound事件内写。
      

  2.   

    你看看e.Row.RowIndex是多少,没准是-1呢,你要判断,不是写在那就不管了
      

  3.   

    e.Row.RowIndex这个你判断对了没有?
      

  4.   

    试在OnRowDataBound事件内写,因为在GridView1_RowCreated事件中相关空间都还没有创建完成,当然获取不到。也可以在其它的事件中,但是一定要等所有相关控件完成
      

  5.   

    试了在DataBound事件里,一样的是同样的错误呢
      

  6.   

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if(e.Row.DataItemIndex>=0)
            {
                ImageButton add = (ImageButton)e.Row.FindControl("add");   
                ....
            }
        }是RowDataBound
      

  7.   


    应该是判断if(e.Row.RowIndex>=0)
      

  8.   

    终于找到解决方法了,可以直接用.e.Row.FindControl就行了的嘛,o(︶︿︶)o 唉,先怎么就没想到呢