You must Sign In to post a response.
  • Category: ASP.NET

    Getting error while insert data using view state in asp.net

    getting error while insert data in viewstate in asp.net

    protected void Button2_Click(object sender, EventArgs e)
    {
    int rowIndex = 0;

    StringCollection sc = new StringCollection();
    if (ViewState["Products"] != null)
    {
    //int saleno = Convert.ToInt16(txtsalesno.Text);
    int saleno = int.Parse(txtsalesno.Text);
    string saldate = txtSalesDate.Text;
    string ddcnt = ddCounterName.Text;
    int prvsbil = int.Parse(txtPreviosBillamount.Text);
    string salprs = ddSalesPerson.Text;
    int txqty = int.Parse(txtqty.Text);
    float txrate = float.Parse(txtrate.Text);
    float disct = float.Parse(txtdispr.Text);
    float dsprs = float.Parse(txtdisrs.Text);
    float txtldis = float.Parse(txttotaldisct.Text);
    float ttldisrupe = float.Parse(txtdisrupes.Text);
    float custrles = float.Parse(txtcustrless.Text);
    float cashrecd = float.Parse(txtcashreceved.Text);
    float txbiamnt = float.Parse(txtbillamountcash.Text);
    float cbalance = float.Parse(txtbalnce.Text);
    DateTime bdte = Convert.ToDateTime(txtbdate.Text);
    string cdte = System.DateTime.Now.ToString("yyyy/MM/dd");
    string saletme = txtsalestime.Text;
    DataTable dtCurrentTable = (DataTable)ViewState["Products"];

    if (dtCurrentTable.Rows.Count > 0)
    {
    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
    {
    //extract the TextBox values
    Label box1 = (Label)ddsales.Rows[rowIndex].Cells[1].FindControl("lblsectn");
    Label box2 = (Label)ddsales.Rows[rowIndex].Cells[2].FindControl("lblproductname");
    Label box3 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lbllotno");
    Label box4 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblmrp");
    Label box5 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblsupliername");
    Label box6 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblsizee");


    sc.Add(saleno + "," + saldate + "," + ddcnt + ","
    + prvsbil + "," + salprs + "," + txqty + ","
    + txrate +"," + disct + "," + dsprs + ","
    + txtldis + "," + ttldisrupe+ "," + custrles + ","
    +cbalance+"," + cashrecd + "," +bdte+","+saletme+","
    + box1.Text +"," + box2.Text + ","
    + box3.Text + "," + box4.Text + "," + txqty+","+box5.Text+","+box6.Text+"," + cdte);
    rowIndex++;
    }

    InsertRecords(sc);
    }
    }

    }
    private void InsertRecords(StringCollection sc)
    {
    SqlConnection conn = new SqlConnection(GetConnectionString());
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    foreach (string item in sc)
    {
    const string sqlStatement = "insert into sales (salesno,salesdate,counername,previousbillamount,salesperson,qty,rate,singledisount,singlerupes,totaldiscount,totalrupes,customerless,balance,cashreceved,bdate,salestime,sectionname,productname,lotno,mrp,quantity,supplername,sizee,currentdate) VALUES";



    if (item.Contains(","))
    {
    splitItems = item.Split(",".ToCharArray());
    sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4], splitItems[5], splitItems[6], splitItems[7], splitItems[8], splitItems[9], splitItems[10], splitItems[11], splitItems[12], splitItems[13], splitItems[14], splitItems[15], splitItems[16], splitItems[17], splitItems[18], splitItems[19], splitItems[20], splitItems[21], splitItems[22], splitItems[23], splitItems[24]);
    }

    }

    try
    {
    conn.Open();
    SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();

    //Display a popup which indicates that the record was successfully inserted
    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

    }
    catch (System.Data.SqlClient.SqlException ex)
    {
    string msg = "Insert Error:";
    msg += ex.Message;
    throw new Exception(msg);

    }
    finally
    {
    conn.Close();
    }
    }
    private string GetConnectionString()
    {
    return System.Configuration.ConfigurationManager.AppSettings["s"].ToString();
    }

    my error is

    Server Error in '/bramandam site' Application.

    Index was outside the bounds of the array.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.

    Source Error:


    Line 760: {
    Line 761: splitItems = item.Split(",".ToCharArray());
    Line 762: sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4], splitItems[5], splitItems[6], splitItems[7], splitItems[8], splitItems[9], splitItems[10], splitItems[11], splitItems[12], splitItems[13], splitItems[14], splitItems[15], splitItems[16], splitItems[17], splitItems[18], splitItems[19], splitItems[20], splitItems[21], splitItems[22], splitItems[23], splitItems[24]);
    Line 763: }
    Line 764:

    Source File: d:\Modified\bramandam site\Salesbfs.aspx.cs Line: 762

    Stack Trace:


    [IndexOutOfRangeException: Index was outside the bounds of the array.]
    Salesbfs.InsertRecords(StringCollection sc) in d:\Modified\bramandam site\Salesbfs.aspx.cs:762
    Salesbfs.Button2_Click(Object sender, EventArgs e) in d:\Modified\bramandam site\Salesbfs.aspx.cs:720
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

    Version Information: Microsoft .NET Framework Version:2.0.50727.3655; ASP.NET Version:2.0.50727.3658
  • #761286
    Hi

    This is your issue
    Index was outside the bounds of the array.
    Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.

    Mostly IndexOutOfRangeException error your collection no have the index value.

    If you using split also your array values did not have then you try to get so we have meet this issue.

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #761287
    Hi
    Can you share your client Side code also then generate your viewstate code.

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #761297
    Hi

    if (dtCurrentTable.Rows.Count > 0)
    {
    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
    This line may be the cause of your error.

    Even when the datatable has zero rows. It will go inside the loop and compare the value of i( i.e. 1<=0) then it will throw you index out of bound Error.

    If this solves your issue, reponse back and mark this answer as best answer.

  • #761300
    Hi

    Something wrong this split section check your index and split values


    if (item.Contains(","))
    {
    splitItems = item.Split(",".ToCharArray());
    sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4], splitItems[5], splitItems[6], splitItems[7], splitItems[8], splitItems[9], splitItems[10], splitItems[11], splitItems[12], splitItems[13], splitItems[14], splitItems[15], splitItems[16], splitItems[17], splitItems[18], splitItems[19], splitItems[20], splitItems[21], splitItems[22], splitItems[23], splitItems[24]);
    }


    working I have attached snapshots given below

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

    Delete Attachment

  • #761305
    kumar i got the same error

  • #761329
    Hi,

    Problem in this line,

    sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4], splitItems[5], splitItems[6], splitItems[7], splitItems[8], splitItems[9], splitItems[10], splitItems[11], splitItems[12], splitItems[13], splitItems[14], splitItems[15], splitItems[16], splitItems[17], splitItems[18], splitItems[19], splitItems[20], splitItems[21], splitItems[22], splitItems[23], splitItems[24]);


    You have total 24 items, but while Appendformat you have added 25 splitItems, you need remove splitItems[24]. This is out side the range that is the reason you got the above error.

    whenever you got any error, first you should try by your self, if you are unable to find the solution then post the error details alone, if you post your full source code with error that's not a good way to raise question. No body is looking full code, everybody having work, we are helping whenever we have time, if you post question like this no body seeing the post.

    Hope you understood...

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #761338
    Hi

    Just Copy Paste This Code

    working for me


    protected void Button2_Click(object sender, EventArgs e)
    {
    int rowIndex = 0;

    StringCollection sc = new StringCollection();
    if (ViewState["Products"] != null)
    {
    //int saleno = Convert.ToInt16(txtsalesno.Text);
    int saleno = int.Parse(txtsalesno.Text);
    string saldate = txtSalesDate.Text;
    string ddcnt = ddCounterName.Text;
    int prvsbil = int.Parse(txtPreviosBillamount.Text);
    string salprs = ddSalesPerson.Text;
    int txqty = int.Parse(txtqty.Text);
    float txrate = float.Parse(txtrate.Text);
    float disct = float.Parse(txtdispr.Text);
    float dsprs = float.Parse(txtdisrs.Text);
    float txtldis = float.Parse(txttotaldisct.Text);
    float ttldisrupe = float.Parse(txtdisrupes.Text);
    float custrles = float.Parse(txtcustrless.Text);
    float cashrecd = float.Parse(txtcashreceved.Text);
    float txbiamnt = float.Parse(txtbillamountcash.Text);
    float cbalance = float.Parse(txtbalnce.Text);
    DateTime bdte = Convert.ToDateTime(txtbdate.Text);
    string cdte = System.DateTime.Now.ToString("yyyy/MM/dd");
    string saletme = txtsalestime.Text;
    DataTable dtCurrentTable = (DataTable)ViewState["Products"];

    if (dtCurrentTable.Rows.Count > 0)
    {
    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
    {
    //extract the TextBox values
    Label box1 = (Label)ddsales.Rows[rowIndex].Cells[1].FindControl("lblsectn");
    Label box2 = (Label)ddsales.Rows[rowIndex].Cells[2].FindControl("lblproductname");
    Label box3 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lbllotno");
    Label box4 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblmrp");
    Label box5 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblsupliername");
    Label box6 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblsizee");


    sc.Add(saleno + "," + saldate + "," + ddcnt + ","
    + prvsbil + "," + salprs + "," + txqty + ","
    + txrate +"," + disct + "," + dsprs + ","
    + txtldis + "," + ttldisrupe+ "," + custrles + ","
    +cbalance+"," + cashrecd + "," +bdte+","+saletme+","
    + box1.Text +"," + box2.Text + ","
    + box3.Text + "," + box4.Text + "," + txqty+","+box5.Text+","+box6.Text+"," + cdte);
    rowIndex++;
    }

    InsertRecords(sc);
    }
    }

    }
    private void InsertRecords(StringCollection sc)
    {
    SqlConnection conn = new SqlConnection(GetConnectionString());
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    foreach (string item in sc)
    {
    const string sqlStatement = "insert into sales (salesno,salesdate,counername,previousbillamount,salesperson,qty,rate,singledisount,singlerupes,totaldiscount,totalrupes,customerless,balance,cashreceved,bdate,salestime,sectionname,productname,lotno,mrp,quantity,supplername,sizee,currentdate) VALUES";



    if (item.Contains(","))
    {
    splitItems = item.Split(",".ToCharArray());
    sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4], splitItems[5], splitItems[6], splitItems[7], splitItems[8], splitItems[9], splitItems[10], splitItems[11], splitItems[12], splitItems[13], splitItems[14], splitItems[15], splitItems[16], splitItems[17], splitItems[18], splitItems[19], splitItems[20], splitItems[21], splitItems[22], splitItems[23]);
    }

    }

    try
    {
    conn.Open();
    SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();

    //Display a popup which indicates that the record was successfully inserted
    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

    }
    catch (System.Data.SqlClient.SqlException ex)
    {
    string msg = "Insert Error:";
    msg += ex.Message;
    throw new Exception(msg);

    }
    finally
    {
    conn.Close();
    }
    }
    private string GetConnectionString()
    {
    return System.Configuration.ConfigurationManager.AppSettings["s"].ToString();
    }


    You have declare this variable

    float txbiamnt = float.Parse(txtbillamountcash.Text);

    But your string collection not have this variable so index mismatch so you meet Index out of range exception. Copy Paste above code.

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #761362
    Hi

    You can go through Below code then you will achieve your output



    int rowIndex = 0;
    StringCollection sc = new StringCollection();
    if (ViewState["Products"] == null)
    {
    //int saleno = Convert.ToInt16(txtsalesno.Text);
    int saleno = int.Parse(txtsalesno.Text);
    string saldate = txtSalesDate.Text;
    string ddcnt = ddCounterName.Text;
    int prvsbil = int.Parse(txtPreviosBillamount.Text);
    string salprs = ddSalesPerson.Text;
    int txqty = int.Parse(txtqty.Text);
    float txrate = float.Parse(txtrate.Text);
    float disct = float.Parse(txtdispr.Text);
    float dsprs = float.Parse(txtdisrs.Text);
    float txtldis = float.Parse(txttotaldisct.Text);
    float ttldisrupe = float.Parse(txtdisrupes.Text);
    float custrles = float.Parse(txtcustrless.Text);
    float cashrecd = float.Parse(txtcashreceved.Text);
    float txbiamnt = float.Parse(txtbillamountcash.Text);
    float cbalance = float.Parse(txtbalnce.Text);
    DateTime bdte = Convert.ToDateTime(txtbdate.Text);
    string cdte = System.DateTime.Now.ToString("yyyy/MM/dd");
    string saletme = txtsalestime.Text;






    DataTable dt1 = new DataTable();
    DataRow dr;
    dt1.Columns.Add("lblsectn");
    dt1.Columns.Add("lblproductname");
    dt1.Columns.Add("lbllotno");
    dt1.Columns.Add("lblmrp");
    dt1.Columns.Add("lblsupliername");
    dt1.Columns.Add("lblsizee");
    dr = dt1.NewRow();
    dr[0] = 1;
    dr[1] = "Mouse";
    dr[2] = 180;
    dr[3] = 123;
    dr[4] = "HCL";
    dr[5] = 196;
    dt1.Rows.Add(dr);

    dr = dt1.NewRow();
    dr[0] = 2;
    dr[1] = "Keyboard";
    dr[2] = 280;
    dr[3] = 323;
    dr[4] = "HCL";
    dr[5] = 496;
    dt1.Rows.Add(dr);


    dr = dt1.NewRow();
    dr[0] = 3;
    dr[1] = "PenDrive";
    dr[2] = 380;
    dr[3] = 423;
    dr[4] = "HCL";
    dr[5] = 696;
    dt1.Rows.Add(dr);

    ddsales.DataSource = dt1;
    ddsales.DataBind();
    ViewState["Products"] = dt1;
    DataTable dtCurrentTable = (DataTable)ViewState["Products"];

    if (dtCurrentTable.Rows.Count > 0)
    {
    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
    {
    //extract the TextBox values
    Label box1 = (Label)ddsales.Rows[rowIndex].Cells[1].FindControl("lblsectn");
    Label box2 = (Label)ddsales.Rows[rowIndex].Cells[2].FindControl("lblproductname");
    Label box3 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lbllotno");
    Label box4 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblmrp");
    Label box5 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblsupliername");
    Label box6 = (Label)ddsales.Rows[rowIndex].Cells[3].FindControl("lblsizee");

    sc.Add(saleno + "," + saldate + "," + ddcnt + ","
    + prvsbil + "," + salprs + "," + txqty + ","
    + txrate + "," + disct + "," + dsprs + ","
    + txtldis + "," + ttldisrupe + "," + custrles + ","
    + cbalance + "," + cashrecd + "," + bdte + "," + saletme + ","
    + box1.Text + "," + box2.Text + ","+ txbiamnt +","
    + box3.Text + "," + box4.Text + "," + txqty + "," + box5.Text + "," + box6.Text + "," + cdte);
    rowIndex++;
    }

    InsertRecords(sc);
    }
    }

    }

    private void InsertRecords(StringCollection sc)
    {
    SqlConnection conn = new SqlConnection(GetConnectionString());
    try
    {
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    foreach (string item in sc)
    {
    const string sqlStatement = "insert into sales (salesno,salesdate,counername,previousbillamount,salesperson,qty,rate,singledisount,singlerupes,totaldiscount,totalrupes,customerless,balance,cashreceved,bdate,salestime,sectionname,productname,lotno,mrp,quantity,supplername,sizee,currentdate) VALUES";
    if (item.Contains(","))
    {
    splitItems = item.Split(",".ToCharArray());
    sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3], splitItems[4], splitItems[5], splitItems[6], splitItems[7], splitItems[8], splitItems[9], splitItems[10], splitItems[11], splitItems[12], splitItems[13], splitItems[14], splitItems[15], splitItems[16], splitItems[17], splitItems[18], splitItems[19], splitItems[20], splitItems[21], splitItems[22], splitItems[23], splitItems[24]);
    }

    }


    conn.Open();
    SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();

    //Display a popup which indicates that the record was successfully inserted
    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

    }
    catch (System.Data.SqlClient.SqlException ex)
    {
    string msg = "Insert Error:";
    msg += ex.Message;
    throw new Exception(msg);

    }
    finally
    {
    conn.Close();
    }


    I have attached snapshots given below.

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

    Delete Attachment


Sign In to post your comments