Click here to Skip to main content
15,891,762 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello in this example the error occurly come like:-

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

pls solve this problem and what pls suggest me what is the reason to come like this error

XML
<%@ Page Language="C#" 
    AutoEventWireup="true" 
    CodeFile="GridViewInsertEditUpdateDelete.aspx.cs" 
    Inherits="GridViewInsertEditUpdateDelete" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="ID" Visible="False">
   <ItemTemplate>
    <asp:Label ID="lblid" runat="server" Text='<%# Eval("id")%>'></asp:Label>
         </ItemTemplate>
    </asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name"> <EditItemTemplate>
  <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewName" runat="server"></asp:TextBox> </FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
  <asp:DropDownList ID="cmbGender" runat="server" SelectedValue='<%# Eval("gender") %>'>
    <asp:ListItem Value="M" Text="Male"></asp:ListItem>
    <asp:ListItem Value="F" Text="Female"></asp:ListItem>
  </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="lbGender" runat="server" Text='<%# Eval("gender") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewGender" runat="server" >
    <asp:ListItem Selected="True" Text="Male" Value="M"></asp:ListItem>
    <asp:ListItem Text="Female" Value="F"></asp:ListItem> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City">
<EditItemTemplate>
  <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewCity" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label3" runat="server" Text='<%# Bind("city") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="State" SortExpression="State">
<EditItemTemplate>
  <asp:Label ID="Label1" runat="server" Text='<%# Eval("state") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
  <asp:TextBox ID="txtNewState" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
  <asp:Label ID="Label4" runat="server" Text='<%# Bind("state") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Type">
<EditItemTemplate>
  <asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="Label5" runat="server" Text='<%# Eval("type") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />

</Columns>
</asp:GridView>
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:customerConnectionString %>"
            SelectCommand="SELECT [id], [name], [gender], [city], [state], [type] FROM [cust_info]">
        </asp:SqlDataSource>
        <br />
        <br />
        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx" Target="_self">To read this article, click here.</asp:HyperLink><br />
        </div>
    </form>
</body>
</html>



i am using class for this example which i send you

C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// Summary description for ClsCustomer
/// </summary>
public class CustomersCls
{

    private string cnstr = ConfigurationManager.ConnectionStrings["customerConnectionString"].ConnectionString;
    private string sql;

    public CustomersCls()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
    {
        string sql = "Insert Into cust_info (name, gender, city, state, type) Values ('" + CustomerName
            + "' , '" + Gender + "', '" + City + "', '" + State + "', '" + CustomerType + "')";
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

    public DataTable Fetch()
    {
        string sql = "Select * From cust_info";
        SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }

   

    public void Update(int CustomerCode, string CustomerName, string Gender, string City, string CustomerType)
    {
        string sql = "UPDATE cust_info SET name='" + CustomerName + "', gender = '" + Gender
            + "', city='" + City + "', type = '" + CustomerType + "' Where id=" + CustomerCode;
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

    public void Delete(int CustomerCode)
    {
        string sql = "Delete cust_info Where id=" + CustomerCode;
        SqlConnection conn = new SqlConnection(cnstr);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        conn.Dispose();
    }

    public DataTable FetchCustomerType()
    {
        string sql = "Select Distinct type From cust_info";
        SqlDataAdapter da = new SqlDataAdapter(sql, cnstr);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }


}
//CREATE TABLE [dbo].[SampleCustomer](
//    [Code] [int] IDENTITY(1,1) NOT NULL,
//    [Name] [varchar](50) NULL,
//    [Gender] [varchar](10) NULL,
//    [City] [varchar](50) NULL,
//    [State] [varchar](50) NULL,
//    [Type] [varchar](50) NULL
//) ON [PRIMARY]

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridViewInsertEditUpdateDelete : System.Web.UI.Page
{
    //SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["customerConnectionString"].ToString());
    CustomersCls customer = new CustomersCls();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillCustomerInGrid();
        }
    }

    private void FillCustomerInGrid()
    {
        DataTable dtCustomer = customer.Fetch();

        if (dtCustomer.Rows.Count > 0)
        {
            GridView1.DataSource = dtCustomer;
            GridView1.DataBind();
        }
        else
        {
            dtCustomer.Rows.Add(dtCustomer.NewRow());
            GridView1.DataSource = dtCustomer;
            GridView1.DataBind();

            int TotalColumns = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GridView1.Rows[0].Cells[0].Text = "No Record Found";
        }

        //SqlDataAdapter adap = new SqlDataAdapter("select * from cust_info", conn);
        //DataSet ds = new DataSet();
        //adap.Fill(ds);
        //GridView1.DataSource = ds;
        //GridView1.DataBind();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtNewName = (TextBox)GridView1.FooterRow.FindControl("txtNewName");
            DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl("cmbNewGender");
            TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl("txtNewCity");
            TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl("txtNewState");
            DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl("cmbNewType");

            customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue);
            FillCustomerInGrid();
        } 
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");

            if (cmbType != null)
            {
                cmbType.DataSource = customer.FetchCustomerType();
                cmbType.DataBind();
                //cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
            }
        }

        if (e.Row.RowType == DataControlRowType.Footer)
        {
            DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
            cmbNewType.DataSource = customer.FetchCustomerType();
            cmbNewType.DataBind();
        } 
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        FillCustomerInGrid(); 
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        customer.Delete(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[1].ToString()));
        FillCustomerInGrid(); 
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        FillCustomerInGrid(); 

        //GridView1.EditIndex = -1;
        //FillCustomerInGrid(); 
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
        DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbGender");
        TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
        DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbType");

        customer.Update(Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString()), txtName.Text, cmbGender.SelectedValue, txtCity.Text, cmbType.SelectedValue);
        GridView1.EditIndex = -1;
        FillCustomerInGrid(); 
    }
}
Posted
Updated 3-Mar-12 2:06am
v2
Comments
OriginalGriff 3-Mar-12 8:06am    
Rather than just dumping your entire code on us, (which is very rude BTW) why not give us a clue?
Edit your post, and cut it down to the error message, and the line it appears on, plus a few lines each side to give us context - the whole method even if it is small as all yours are.
Then we wouldn't have to guess...
#realJSOP 3-Mar-12 8:08am    
Where EXACTLY are you seeing this exception? We're not inclined to wade through code trying to find the problem on our own. Further, the HTML portion appears to have absolutely NO BEARING on the question.

1 solution

Use a debugger and tell the debugger to stop on exceptions. When the exception occurcs, you will know more exactly where the error occurs. You will probably also know the index (and for which array) where the problem occurs.

But he way, instead of dumping code, you should have post just the problematic lines. You can always comment out some code to see if the problem still appears.

You don't even tell us if the problem occurs on initial filling or when adding, editing or deleting a row. And also does you have any data when the problem occurs. By the way, it look like when no record are found that you fill only the first column but if the row is deleted, the second column is also used.

By the way, it is a very bad practice to uses hard-coded constant for your column index. It will be a maintenance nightmare if you decide to add a new column before the last one as you will have to go through all the code and carefully check each number to see if they need to be adjusted. At minimum use a private constant in your class for the index of each column. That way, if you reorder them, you only have to update those constant and not all function in your class.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 3-Mar-12 19:27pm    
Good points, a 5.
--SA

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