assigning values to array

nescartel

Member
Joined
Jun 10, 2007
Messages
22
Programming Experience
3-5
hello,
i have this simple application that writes and reads from text file.
it is working fine, here's the code:

VB.NET:
   Private Sub btnTestRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestRead.Click

        Dim StringTemp As String
        Dim i As Integer = 0

        Using Reader As StreamReader = New StreamReader("User.cfg")

            Do
                StringTemp = Reader.ReadLine()
                MsgBox(StringTemp)
                i = i + 1

            Loop Until StringTemp Is Nothing

            Reader.Close()
        End Using
    End Sub

    Private Sub btnTestWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestWrite.Click

        Using Writer As StreamWriter = New StreamWriter("User.cfg")

            Dim asd As String = "1st line"

            Writer.WriteLine(asd)
            Writer.WriteLine("2nd line, testing.. testing...")

            Writer.Close()
        End Using
    End Sub

however, in the streamreader,
i need to store each line that is read from text file into an array,
so that i can manipulate and edit, and then write it again.
here's the modified streamreader sub:
(i've highlighted the additional code)

VB.NET:
    Private Sub btnTestRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestRead.Click

        Dim StringTemp As String
        Dim i As Integer = 0
        [B]Dim MyArray() As String = Nothing[/B]

        Using Reader As StreamReader = New StreamReader("User.cfg")

            Do
                StringTemp = Reader.ReadLine()
                [B]MyArray(i) = StringTemp[/B]
                MsgBox(StringTemp)
                i = i + 1

            Loop Until StringTemp Is Nothing

            Reader.Close()
        End Using
    End Sub

it is just a simple array with incrementing index that will store each line in a different cell. however, i get an exception error:

VB.NET:
System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="DiagnoseII"
  StackTrace:
       at WindowsApplication1.Form2.btnTestRead_Click(Object sender, EventArgs e) in D:\VB\Projects\Diagnose\DiagnoseII\DiagnoseII\Form2.vb:line 62
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at WindowsApplication1.Form1.btnMemory_Click(Object sender, EventArgs e) in D:\VB\Projects\Diagnose\DiagnoseII\DiagnoseII\Form1.vb:line 920
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

provided the exception message, i changed my code to use the 'new' keyword, and it has now become:

VB.NET:
    Private Sub btnTestRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestRead.Click

        Dim StringTemp As String
        Dim i As Integer = 0
        Dim MyArray() As String = Nothing

        Using Reader As StreamReader = New StreamReader("User.cfg")

            Do
                StringTemp = Reader.ReadLine()
                MyArray(i) = [B]New String([/B]StringTemp[B])[/B]
                MsgBox(StringTemp)
                i = i + 1

            Loop Until StringTemp Is Nothing

            Reader.Close()
        End Using


but i'm still getting the exception handling error:

VB.NET:
System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object."
  Source="DiagnoseII"
  StackTrace:
       at WindowsApplication1.Form2.btnTestRead_Click(Object sender, EventArgs e) in D:\VB\Projects\Diagnose\DiagnoseII\DiagnoseII\Form2.vb:line 62
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at WindowsApplication1.Form1.btnMemory_Click(Object sender, EventArgs e) in D:\VB\Projects\Diagnose\DiagnoseII\DiagnoseII\Form1.vb:line 920
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

what am i doing wrong?
i just want to save every lines read from text file into array,
i don't think it should be THIS frustating? :confused:
 
Try This

You better go for arraylist usage instead of array.It can dynamically increase & decrease whenever required.Using enumerator you can assighn each line to the arraylist.Al de best
 
"Dim MyArray() As String", array have zero elements. You have to dimension it initially "Dim MyArray(23) As String" or redimension it dynamically with the ReDim statement and also preserve the array content with the Preserve directive "ReDim Preserve MyArray(4)", you could also use "Array.ReSize(MyArray, 5)".

As mentioned you are better off using a collection, use List(Of String), not ArrayList (of Object type).
 
hello,
what am i doing wrong?

Well, when the program crashes, you get a box pointing to the line that the crash occurred on. In "Object ref not set to an instance" it means one of your objects youre attempting to use, is not set to anything

In the context of:

MyArray(i) = StringTemp

it cannot be stringtemp, because even if stringtemp WAS Nothing, the assignment would still proceed. The error is in MyArray, which you are attempting to use by saying:

MyArray(i)

If you point the mouse cursor at the word "MyArray" it should say "Nothing" in the tooltip.. and because it is set to Nothing, you cant use it.

Use the debugger as much as possible to investigate problem lines. This is a very simple error in OO programming and quickly solved with the debugger's help. :)
 
owh... i can see it clear now. :D

i assigned the array to have 100 elements,
and later on use array.resize to cut the unnecessary elements off.
many thanx to you guys, CHEERS! :cool:
 
As the others have recommended, you can largely avoid using arrays these days; their usefulness is usually limited to situations where you know the number of items youre storing. Use List(Of String) instead
 
List(Of T) is a strongly typed collection, which is similar to array but manages the storage itself, with array you have to redimension it and manage indexing yourself, the collection have convenient methods for adding and removing items. Arrays can't be changed inherently so each time you redeclare size a new one is created, if you also preserve then each item is internally copied from source array to next, so there is also a preformance issue with arrays that collections have a managed solution for internally. There are also different type collections other than plain list that add specialized features you would have to code a lot to achieve the same with plain arrays, and for what? You wouldn't have gained anything but lost time.
 
thank you for the detailed insight JohnH,
i find it very enlightening! :)

currently i managed to read text file, store in array, edit and then write again to text file. but i am now trying the List(Of T), since array is not that efficient. i declared my array initially to Array(100), and since the index will only use not greater than 10, why should i waste resource right?

am now studying tutorials on List(Of T)... :D

will remove the array once i understand List... thanx again, you are most helpful, peace...
 
Back
Top