Click here to Skip to main content
15,911,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a gridviewID 'gvtest' I get an error stating as :
'Index is out of range. Must be non-negative and less than the size of collection'
I submit the codes I have used.
XML
<asp:GridView ID="gvtest1" runat="server" AutoGenerateColumns="False"
            style="z-index: 1; left: 68px; top: 60px; position: absolute; height: 105px; width: 390px; background-color: #ECE9D8;"
           DataSourceID="SqlDataSource1"
            HorizontalAlign="Center" BorderColor="Maroon" ForeColor="#CC9900">
         <Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>


C#
protected void btnProcess_Click(object sender, EventArgs e)
  {

      string str = string.Empty;
      string strname = string.Empty;
      string v_amt = string.Empty;

      foreach (GridViewRow gvrow in gvtest1.Rows)
      {
          CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
          if (chk != null & chk.Checked)
          {
              //str += gvtest.Rows[gvrow.RowIndex].Value.ToString() + ',';
              str += gvtest1.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
              strname += gvrow.Cells[2].Text + ',';
              v_amt += gvrow.Cells[5].Text + ',';
              string v_stringamt = gvrow.Cells[5].Text;
              int v_amt1 = Convert.ToInt32(v_stringamt);

              v_totamt = (v_totamt + v_amt1);
          }
      }


Can anyone help me out?
Posted
Comments
Hemant Singh Rautela 5-May-13 7:25am    
I think here is problem " gvrow.Cells[5].Text ",

Check out in your gridview how many columns are there ... I think there may be less than 6 columns are there so that you getting this problem... index starts from 0....

Better thing is there use column name instead of column no.

1 solution

It simply means that you are trying to access an index that does not exists.

For example:
You define an array A of 10 elements. When you try to access A[15] you will get an index out of range error. Since you defined 10 elements, valid values are from 0 to 9 only.

Now, use Visual Studio debug and see when & where you get it. Correct your logic there.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900