Question how to fix error

Georgez

Member
Joined
Dec 26, 2010
Messages
7
Programming Experience
Beginner
I'm trying to make a xml file using random numbers with name of user' but I get a NullReferenceException was unhandled
I have a start button, stop button, label and a text box and dont know if anything is set right. Please help

VB.NET:
Public Class Form1

    'Random to fake a score
    Dim rnd As New Random
    Dim userName As XElement
    Dim newUser As XAttribute
    Dim scoresDoc As XDocument
    Dim userData As XElement
    Dim highScore As Integer = 0

    Private Sub btnStartGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartGame.Click

        scoresDoc = XDocument.Load("C:\Temp\HighScores.xml")

        'Load User
        userData = (From node In scoresDoc.Descendants("User")
                       Where node.Attribute("name").Value = userName
                       Select node).FirstOrDefault


        lblHighScore.Text = "highScore"
        'Set High Score if User is returning
        If userData IsNot Nothing Then
            highScore = CInt(userData.<HighScore>.Value)
            lblHighScore.Text = "highScore"
        End If
    End Sub
    Private Sub btnEndGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEndGame.Click
        Dim currentScore = rnd.Next(1, 1001)

        'Check if User exists
        If userData IsNot Nothing Then
            If currentScore > highScore Then
                'Update HighScore element
                userData.SetElementValue("HighScore", currentScore)
                MessageBox.Show("New High Score of " & currentScore.ToString() & "!")
                highScore = currentScore
                lblHighScore.Text = "highScore"
            End If
        Else
            'Create a user
            Dim newUser = <User name=<%= userName %>>
                              <HighScore><%= currentScore %></HighScore>
                          </User>


            scoresDoc.Element("Root").Add(newUser)
        End If

        scoresDoc.Save("C:\Temp\HighScores.xml")
    End Sub

    
End Class
 
MattP is the best

vb 2010 express
I am new to this and
I saw your code and liked what i saw so
this is what I have up to this point
stops running at
scoresDoc.Element("Root").Add(newUser)
and I get a NullReferenceException was unhandled
Thanks again
VB.NET:
Public Class Form1

    'Random to fake a score
    Dim rnd As New Random
    Dim userName As String
    Dim scoresDoc As XDocument
    Dim userData As XElement
    Dim highScore As Integer = 0

    Private Sub btnStartGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartGame.Click
        userName = txtUserName.Text
        scoresDoc = XDocument.Load(Application.StartupPath + "\HighScores.xml")

        'Load User
        userData = (From node In scoresDoc.Descendants("User")
                       Where node.Attribute("name").Value = userName
                       Select node).FirstOrDefault

        'Set High Score if User is returning
        If userData IsNot Nothing Then
            highScore = CInt(userData.<HighScore>.Value)

        End If
    End Sub
    Private Sub btnEndGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEndGame.Click
        Dim currentScore = rnd.Next(1, 1001)

        'Check if User exists
        If userData IsNot Nothing Then
            If currentScore > highScore Then
                'Update HighScore element
                userData.SetElementValue("HighScore", currentScore)
                MessageBox.Show("New High Score of " & currentScore.ToString() & "!")

                highScore = currentScore
                lb1HighScore.Text = highScore
            End If
        Else
            'Create a user
            Dim newUser = <User name=<%= userName %>>
                              <HighScore><%= currentScore %></HighScore>
                          </User>


            scoresDoc.Element("Root").Add(newUser)
        End If

        scoresDoc.Save(Application.StartupPath + "\HighScores.xml")
    End Sub

End Class
 
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=xmlplayer
StackTrace:
at xmlplayer.Form1.btnEndGame_Click(Object sender, EventArgs e) in C:\Documents and Settings\George\my documents\visual studio 2010\Projects\xmlplayer\xmlplayer\Form1.vb:line 45
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(IntPtr 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 xmlplayer.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly 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, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
 
I'm running that code with no problem. Have you tried taking a look at the HighScores.xml file in your bin/Debug folder?

The base file from the example should look like this:

VB.NET:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
</Root>
 
I got your csv high score project to work
but still getting NullReferenceException was unhandled in the XML project
the HighScores.xml is correct and in the bin/debug folder
something is not working in scoresDoc.Element("Root").Add(newUser)
Add.(newUser) is showing userName and currentScore
I dont seem to be pulling any data out of
userData = (From node In scoresDoc.Descendants("User")
Where node.Attribute("name").Value = userName
Select node).FirstOrDefault
userData is null
 
Think I got it
had the XML file as a word file put it to the notepad then saved it seems to be working now thanks alot love your projects
 
Back
Top