C# StringCollection: Exception of type 'System.OutOfMemoryException' was thrown.

Last Reply on Jul 23, 2014 06:23 AM By Azim

Posted on Jul 22, 2014 06:23 AM

Hi I refer in this tutorial

http://www.aspsnippets.com/Articles/Adding-Dynamic-Rows-in-ASP.NET-GridView-Control-with-TextBoxes-and-with-Delete-functionality.aspx

So I try to add some textbox

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Dynamic textbox Scratch.aspx.vb" Inherits="Dynamic_textbox_Scratch" %>

<!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></title>
    <style type="text/css">

  
table { 
  margin: 10px 0 30px 0;
}

* { 
  margin: 0; 
  padding: 0;
            height: 26px;
        }

table tr th, table tr td { 
  background: #3B3B3B;
  color: #FFF;
  padding: 7px 4px;
  text-align: left;
}
  
table tr td { 
  background: #E5E5DB;
  color: #47433F;
  border-top: 1px solid #FFF;
}

a, a:hover { 
  outline: none;
  text-decoration: underline;
  color: #03D1FD;
}

    </style>
</head>
<body>
    <form id="form1" runat="server">
        
    <div>
    
        <asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="false" 
            onrowcreated="Gridview1_RowCreated" ShowFooter="true">
            <Columns>
                
                <asp:TemplateField HeaderText="FROM">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="TO">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="POSITION TITLE">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                    </ItemTemplate>

                    </asp:TemplateField>
                <asp:TemplateField HeaderText="DEPARTMENT/AGENCY">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                    </ItemTemplate>

                    </asp:TemplateField>
                <asp:TemplateField HeaderText="MONTHLY SALARY">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                    </ItemTemplate>

                    </asp:TemplateField>
                <asp:TemplateField HeaderText="STATUS OF APPOINTMENT">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                    </ItemTemplate>

                    <FooterStyle HorizontalAlign="Right" />
                    <FooterTemplate>
                        <asp:Button ID="ButtonAdd" runat="server" onclick="ButtonAdd_Click" 
                            Text="Add New Row" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">Remove</asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
    
    </div>
    </form>
</body>
</html>

And the I edit the VB codes

Private Sub SetInitialRow()
        Dim dt As DataTable = New DataTable
        Dim dr As DataRow = Nothing
        'dt.Columns.Add(New DataColumn("RowNumber", GetType(System.String)))
        dt.Columns.Add(New DataColumn("Column1", GetType(System.String)))
        dt.Columns.Add(New DataColumn("Column2", GetType(System.String)))
        dt.Columns.Add(New DataColumn("Column3", GetType(System.String)))
        dt.Columns.Add(New DataColumn("Column4", GetType(System.String)))
        dt.Columns.Add(New DataColumn("Column5", GetType(System.String)))
        dt.Columns.Add(New DataColumn("Column6", GetType(System.String)))
        dr = dt.NewRow
        'dr("RowNumber") = 1
        dr("Column1") = String.Empty
        dr("Column2") = String.Empty
        dr("Column3") = String.Empty
        dr("Column4") = String.Empty
        dr("Column5") = String.Empty
        dr("Column6") = String.Empty
        dt.Rows.Add(dr)
        'dr = dt.NewRow();
        'Store the DataTable in ViewState
        ViewState("CurrentTable") = dt
        Gridview1.DataSource = dt
        Gridview1.DataBind()
    End Sub

    Private Sub AddNewRowToGrid()
        Dim rowIndex As Integer = 0
        If (Not (ViewState("CurrentTable")) Is Nothing) Then
            Dim dtCurrentTable As DataTable = CType(ViewState("CurrentTable"), DataTable)
            Dim drCurrentRow As DataRow = Nothing
            If (dtCurrentTable.Rows.Count > 0) Then
                Dim i As Integer = 1
                Do While (i <= dtCurrentTable.Rows.Count)
                    'extract the TextBox values
                    Dim box1 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
                    Dim box2 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
                    Dim box3 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(3).FindControl("TextBox3"), TextBox)
                    Dim box4 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(4).FindControl("TextBox4"), TextBox)
                    Dim box5 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(5).FindControl("TextBox5"), TextBox)
                    Dim box6 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(6).FindControl("TextBox6"), TextBox)
                    drCurrentRow = dtCurrentTable.NewRow
                    'drCurrentRow("RowNumber") = (i + 1)
                    drCurrentRow("Column1") = box1.Text
                    drCurrentRow("Column2") = box2.Text
                    drCurrentRow("Column3") = box3.Text
                    drCurrentRow("Column4") = box4.Text
                    drCurrentRow("Column5") = box5.Text
                    drCurrentRow("Column6") = box6.Text
                    rowIndex = (rowIndex + 1)
                    i = (i + 1)
                Loop
                dtCurrentTable.Rows.Add(drCurrentRow)
                ViewState("CurrentTable") = dtCurrentTable
                Gridview1.DataSource = dtCurrentTable
                Gridview1.DataBind()
            End If
        Else
            Response.Write("ViewState is null")
        End If
        'Set Previous Data on Postbacks
        SetPreviousData()
    End Sub

    Private Sub SetPreviousData()
        Dim rowIndex As Integer = 0
        If (Not (ViewState("CurrentTable")) Is Nothing) Then
            Dim dt As DataTable = CType(ViewState("CurrentTable"), DataTable)
            If (dt.Rows.Count > 0) Then
                Dim i As Integer = 1
                Do While (i < dt.Rows.Count)
                    Dim box1 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
                    Dim box2 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
                    Dim box3 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(3).FindControl("TextBox3"), TextBox)
                    Dim box4 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(4).FindControl("TextBox4"), TextBox)
                    Dim box5 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(5).FindControl("TextBox5"), TextBox)
                    Dim box6 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(6).FindControl("TextBox6"), TextBox)
                    box1.Text = dt.Rows(i)("Column1").ToString
                    box2.Text = dt.Rows(i)("Column2").ToString
                    box3.Text = dt.Rows(i)("Column3").ToString
                    box4.Text = dt.Rows(i)("Column4").ToString
                    box5.Text = dt.Rows(i)("Column5").ToString
                    box6.Text = dt.Rows(i)("Column6").ToString
                    rowIndex = (rowIndex + 1)
                    i = (i + 1)
                Loop
            End If
            ' ViewState["CurrentTable"] = dt;
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            SetInitialRow()
        End If
    End Sub

    Protected Sub ButtonAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
        AddNewRowToGrid()
    End Sub

    'A method that returns a string which calls the connection string from the web.config
    Private Function GetConnectionString() As String
        '"DBConnection" is the name of the Connection String
        'that was set up from the web.config file
        Return System.Configuration.ConfigurationManager.ConnectionStrings("EmployeesConnectionString").ConnectionString
    End Function

    'A method that Inserts the records to the database
    Private Sub InsertRecords(ByVal sc As StringCollection)
        Dim conn As SqlConnection = New SqlConnection(GetConnectionString)
        Dim sb As StringBuilder = New StringBuilder(String.Empty)
        Dim splitItems() As String = Nothing
        For Each item As String In sc
            Const sqlStatement As String = "INSERT INTO SampleTable (Column1,Column2,Column3,Column4,Column5,Column6) VALUES"
            If item.Contains(",") Then
                splitItems = item.Split(",".ToCharArray)
                sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2), splitItems(3), splitItems(4), splitItems(5))
            End If
        Next
        Try
            conn.Open()
            Dim cmd As SqlCommand = New SqlCommand(sb.ToString, conn)
            cmd.CommandType = CommandType.Text
            cmd.ExecuteNonQuery()
            Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
        Catch ex As System.Data.SqlClient.SqlException
            Dim msg As String = "Insert Error:"
            msg = (msg + ex.Message)
            Throw New Exception(msg)
        Finally
            conn.Close()
        End Try
    End Sub

    ' Hide the Remove Button at the last row of the GridView
    Protected Sub Gridview1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles Gridview1.RowCreated
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim dt As DataTable = CType(ViewState("CurrentTable"), DataTable)
            Dim lb As LinkButton = CType(e.Row.FindControl("LinkButton1"), LinkButton)
            If (Not (lb) Is Nothing) Then
                If (dt.Rows.Count > 1) Then
                    If (e.Row.RowIndex = (dt.Rows.Count - 1)) Then
                        lb.Visible = False
                    End If
                Else
                    lb.Visible = False
                End If
            End If
        End If
    End Sub

    Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim lb As LinkButton = CType(sender, LinkButton)
        Dim gvRow As GridViewRow = CType(lb.NamingContainer, GridViewRow)
        Dim rowID As Integer = (gvRow.RowIndex + 1)
        If (Not (ViewState("CurrentTable")) Is Nothing) Then
            Dim dt As DataTable = CType(ViewState("CurrentTable"), DataTable)
            If (dt.Rows.Count > 1) Then
                If (gvRow.RowIndex < (dt.Rows.Count - 1)) Then
                    'Remove the Selected Row data
                    dt.Rows.Remove(dt.Rows(rowID))
                End If
            End If
            'Store the current data in ViewState for future reference
            ViewState("CurrentTable") = dt
            'Re bind the GridView for the updated data
            Gridview1.DataSource = dt
            Gridview1.DataBind()
        End If
        'Set Previous Data on Postbacks
        SetPreviousData()
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim rowIndex As Integer = 0
        Dim sc As StringCollection = New StringCollection
        If (Not (ViewState("CurrentTable")) Is Nothing) Then
            Dim dtCurrentTable As DataTable = CType(ViewState("CurrentTable"), DataTable)
            If (dtCurrentTable.Rows.Count > 0) Then
                Dim i As Integer = 1
                Do While (i <= dtCurrentTable.Rows.Count)
                    'extract the TextBox values
                    Dim box1 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
                    Dim box2 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
                    Dim box3 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(3).FindControl("TextBox3"), TextBox)
                    Dim box4 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(4).FindControl("TextBox4"), TextBox)
                    Dim box5 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(5).FindControl("TextBox5"), TextBox)
                    Dim box6 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(6).FindControl("TextBox6"), TextBox)
                    'get the values from the TextBoxes
                    'then add it to the collections with a comma "," as the delimited values
                    sc.Add((box1.Text + ("," + (box2.Text + ("," + box3.Text + ("," + box4.Text + ("," + (box5.Text + ("," + (box6.Text))))))))))
                    'rowIndex = (rowIndex + 1)
                    'i = (i + 1)
                Loop
                'Call the method for executing inserts
                InsertRecords(sc)
            End If
        End If
    End Sub

But I get the error of

Exception of type 'System.OutOfMemoryException' was thrown.

 

Thanks :D

You are viewing reply posted by: Azim on Jul 23, 2014 06:23 AM.
Posted on Jul 23, 2014 06:23 AM

This error comes when you are loading huge data to memory stream and your system memory is not capable of storing this much data.

Also you are keep adding data to StringCollection in while loop so it will create lots of data

You can refer

http://stackoverflow.com/questions/356645/exception-of-type-system-outofmemoryexception-was-thrown-why

http://stackoverflow.com/questions/4907931/exception-of-type-system-outofmemoryexception-was-thrown

http://stackoverflow.com/questions/8134872/exception-of-type-system-outofmemoryexception-was-thrown