Storage issue with linked list VB.NET - vb.net

i am using vb.net to create a linked list, and am finding an issue with storage. the second to last value entered is always deleted. i believe this issue is in the Add() subroutine, but i cant figure out how this is caused, or how to fix it. attached is the code and ss of the console. console output
Module Program
Structure linkedList
Dim item As String
Dim position As Integer
Dim pointer As Decimal
Dim isEmpty As Boolean
End Structure
Dim tail As Integer
Dim input As String
Dim list(30) As linkedList
Dim index As Integer
Const head As Integer = 0
Dim menuChoice As Integer
Sub Main()
For i = 0 To list.Length - 1 : list(i).isEmpty = True : Next
menu()
End Sub
Sub menu()
Do
Try
Console.WriteLine("Press 1 to add values, 2 to remove them.")
menuChoice = Console.ReadLine
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Loop Until menuChoice = 1 Or menuChoice = 2
Select Case menuChoice
Case 1
add()
Case 2
remove()
End Select
End Sub
Sub add()
list(0).position = -1
list(0).item = "Head"
index = 1
Do
Console.WriteLine("Enter a value to enter into the linked list, or press X to stop: ")
input = Console.ReadLine
If input <> "X" And input <> vbNullString Then
For i = 0 To list.Length - 1
If list(i).isEmpty = True Then
list(i + 1).item = input
list(i + 1).position = index
list(i + 1).pointer = index + 1
list(i).isEmpty = False
Exit For
End If
Next
End If
list(0).pointer = findNextAvailable(0)
If input <> "X" Then : index += 1 : End If
If input = "X" Then
tail = index
End If
Loop Until input = "X" Or index = 30
showList()
End Sub
Sub remove()
Dim checked As Boolean = False
Dim removString As String
Dim removPos As Integer
Dim removPoint As Integer
Dim num1 As Integer
Do
Try
Console.WriteLine("Enter a string to remove from the Linked List:")
removString = Console.ReadLine.Trim
For i = 0 To list.Length - 1
If list(i).item = removString Then
checked = True
removPos = i
num1 = i - 1
list(i).isEmpty = True
Exit For
Else
checked = False
list(i).isEmpty = False
End If
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Loop Until checked = True
list(removPos).item = vbNullString
list(removPos).pointer = fixPointer(num1)
list(num1).pointer = findPos(removPos)
showList()
End Sub
Function findPos(start As Integer) As Integer
Dim check As Boolean
Dim num1 As Integer
For i = start To list.Length - 1
If list(i).item <> vbNullString Then
check = True
num1 = i - 1
Exit For
End If
Next
If check = True Then
Return num1
Else
Return vbNullString
End If
End Function
Function findNextAvailable(startPoint As Integer) As Integer
Dim nextAvailableTrue As Boolean
Dim num1 As Integer
For i = startPoint To 0 Step -1
If list(i).item <> vbNullString Then
nextAvailableTrue = True
num1 = i
Exit For
End If
Next
If nextAvailableTrue Then
Return num1 + 1
Else
Return startPoint + 1
End If
End Function
Function fixPointer(r As Integer) As Integer
Dim i As Integer = 0
Dim check As Boolean = False
Do
If list(i).item <> vbNullString Then
check = True
End If
i += 1
Loop Until check = True
For x = 0 To list.Length - 1
If list(x).pointer <> vbNull And list(x).item = vbNullString Then
list(x).pointer = vbNull
End If
Next
list(r).pointer = list(i).position
Return list(r).pointer
End Function
Sub showList()
Dim lastPosition As Integer = 0
For x = 0 To list.Length - 1
If list(x).isEmpty Then
list(x).pointer = 0
list(x).position = x
End If
If list(x).isEmpty = False Then
lastPosition = list(x).position
End If
Next
list(lastPosition).item = vbNullString
list(lastPosition).pointer = 0.0
For i = 0 To list.Length - 1
Console.WriteLine($"{list(i).position} ¦ {list(i).item} ¦ {list(i).pointer}")
Next
Console.ReadLine()
menu()
End Sub
End Module

Related

Writing a matrix to a text file

So i have done how to read a matrix from a text file where the first line defines the elements, however my question is how would i do the opposite that would write to the text file. I would like it to ask the user for the row 0 column 0, and add on, and have this code to write into the console, but do not know how to do into a text file
This is the code to write into console:
Dim size As Integer = 3
Dim numberWidth As Integer = 2
Dim format As String = "D" & numberWidth
Dim A(size - 1, size - 1) As Integer
For i As Integer = 0 To A.GetUpperBound(0)
For j As Integer = 0 To A.GetUpperBound(1)
Console.Write(String.Format("Enter The Matrix Element at A[Row {0}, Col {1}]: ", i, j))
A(i, j) = Convert.ToInt16(Console.ReadLine())
Next
Next
This is code for reading the matrix
Dim path = "d:\matrix.txt"
Dim A(,) As Integer
Using reader As New IO.StreamReader(path)
Dim size = reader.ReadLine() ' read first line which is the size of the matrix (assume the matrix is a square)
Redim A(size - 1, size - 1)
Dim j = 0 ' the current line in the matrix
Dim line As String = reader.ReadLine() ' read next line
Do While (line <> Nothing) ' loop as long as line is not empty
Dim numbers = line.Split(" ") ' split the numbers in that line
For i = 0 To numbers.Length - 1
A(j, i) = numbers(i) ' copy the numbers into the matrix in current line
Next
j += 1 ' increment the current line
line = reader.ReadLine() ' read next line
Loop
End Using
Console.WriteLine("Matrix A :")
Dim numberWidth As Integer = 2
Dim format As String = "D" & numberWidth
For i As Integer = 0 To A.GetUpperBound(0)
Console.Write("| ")
For j As Integer = 0 To A.GetUpperBound(1)
Console.Write("{0} ", A(i, j).ToString(format))
Next
Console.WriteLine("|")
Next
Save function:
Dim A(,) As Integer
Sub SaveMatrix()
Dim path As String = "z:\matrix.txt"
Using fs As New System.IO.FileStream(path, IO.FileMode.OpenOrCreate)
fs.SetLength(0) ' reset file length to 0 in case we are overwriting an existing file
Using sw As New System.IO.StreamWriter(fs)
Dim line As New System.Text.StringBuilder
sw.WriteLine((A.GetUpperBound(0) + 1).ToString()) ' size of array in first line
For i As Integer = 0 To A.GetUpperBound(0)
line.Clear()
For j As Integer = 0 To A.GetUpperBound(1)
line.Append(A(i, j).ToString() & " ")
Next
sw.WriteLine(line.ToString().Trim()) ' output each row to the file
Next
End Using
End Using
Console.WriteLine("")
Console.WriteLine("Matrix successfully saved to:")
Console.WriteLine(path)
End Sub
I have created a class for the Matrix data and the a List(of T) so you con't have to worry about changing the size of an array.
I am using Interpolated strings which is a replacement for String.Format in some cases and easier to read.
I have overriden the .ToString method in the MatrixItem class to make it easy to save the objects to a text file.
Other comments in-line.
Public Sub Main()
Dim A As List(Of MatrixItem) = CreateListOfMatrixItem()
SaveMatrixList(A)
ViewMatrixFile()
Console.ReadLine()
End Sub
Private Function CreateListOfMatrixItem() As List(Of MatrixItem)
Dim A As New List(Of MatrixItem)
Dim HowManyRows As Integer = 3
For i As Integer = 0 To HowManyRows - 1
Dim M As New MatrixItem()
For j As Integer = 0 To 2
Console.WriteLine($"Enter The Matrix Element at A[Row {i}, Col {j}]: ")
Select Case j
Case 0
M.X = Convert.ToInt16(Console.ReadLine())
Case 1
M.Y = Convert.ToInt16(Console.ReadLine())
Case 2
M.Z = Convert.ToInt16(Console.ReadLine())
End Select
Next
A.Add(M)
Next
Return A
End Function
Private Sub SaveMatrixList(A As List(Of MatrixItem))
Dim sb As New StringBuilder
For Each item In A
sb.AppendLine(item.ToString)
Next
'this will open or create the file and append the new data
'if you want to overwrite the contents of the file then
'use File.WriteAllText("Matrix.txt", sb.ToString)
File.AppendAllText("Matrix.txt", sb.ToString)
End Sub
Private Sub ViewMatrixFile()
Dim lines = File.ReadAllLines("Matrix.txt")
Console.WriteLine($"{"X",10}{"Y",10}{"Z",10}")
For Each line In lines
Dim numbers = line.Split(","c)
'To format the values with the a numeric format it is necessary to convert the
'strings to a numeric type.
Console.WriteLine($"{CInt(numbers(0)),10:D2}{CInt(numbers(1)),10:D2}{CInt(numbers(2)),10:D2}")
Next
End Sub
Public Class MatrixItem
Public Property X As Int16
Public Property Y As Int16
Public Property Z As Int16
Public Overrides Function ToString() As String
Return $"{X},{Y},{Z}"
End Function
End Class
Here's a framework to build upon demonstrating how to enter, save, and load your matrices. You can add other options to the menu based on what other operations you need to implement:
Module Module1
Public A(,) As Integer
Public Sub Main()
Dim response As String
Dim quit As Boolean = False
Do
Console.WriteLine("")
Console.WriteLine("--- Menu Options ---")
Console.WriteLine("1) Enter a Matrix")
Console.WriteLine("2) Display Matrix")
Console.WriteLine("3) Save Matrix")
Console.WriteLine("4) Load Matrix")
Console.WriteLine("5) Quit")
Console.Write("Menu choice: ")
response = Console.ReadLine()
Console.WriteLine("")
Select Case response
Case "1"
EnterMatrix()
Case "2"
DisplayMatrix()
Case "3"
SaveMatrix()
Case "4"
LoadMatrix()
Case "5"
quit = True
Case Else
Console.WriteLine("")
Console.WriteLine("Invalid Menu Choice")
End Select
Loop While (Not quit)
Console.Write("Press any key to dismiss the console...")
Console.ReadKey()
End Sub
Public Sub EnterMatrix()
Dim valid As Boolean
Dim size, value As Integer
Console.Write("Enter the Size of the Square Matrix: ")
Dim response As String = Console.ReadLine()
If Integer.TryParse(response, size) Then
If size >= 2 Then
Console.WriteLine("")
ReDim A(size - 1, size - 1)
For i As Integer = 0 To A.GetUpperBound(0)
Console.WriteLine("--- Row " & i & " ---")
For j As Integer = 0 To A.GetUpperBound(1)
valid = False
Do
Console.Write(String.Format("Enter The Matrix Element at A[Row {0}, Col {1}]: ", i, j))
response = Console.ReadLine()
If Integer.TryParse(response, value) Then
A(i, j) = value
valid = True
Else
Console.WriteLine("")
Console.WriteLine("Matrix Element must be a valid Integer!")
Console.WriteLine("")
End If
Loop While (Not valid)
Next
Console.WriteLine("")
Next
Else
Console.WriteLine("")
Console.WriteLine("Size must be greater than or equal to 2!")
End If
Else
Console.WriteLine("")
Console.WriteLine("Invalid Size")
End If
End Sub
Public Sub DisplayMatrix()
If Not IsNothing(A) AndAlso A.Length > 0 Then
Dim maxLength As Integer = Integer.MinValue
For i As Integer = 0 To A.GetUpperBound(0)
For j As Integer = 0 To A.GetUpperBound(1)
maxLength = Math.Max(maxLength, A(i, j).ToString.Length)
Next
Next
Console.WriteLine("Matrix Contents:")
For i As Integer = 0 To A.GetUpperBound(0)
Console.Write("| ")
For j As Integer = 0 To A.GetUpperBound(1)
Console.Write("{0} ", A(i, j).ToString().PadLeft(maxLength, " "))
Next
Console.WriteLine("|")
Next
Else
Console.WriteLine("The Matrix is empty!")
End If
End Sub
Public Sub SaveMatrix()
If Not IsNothing(A) AndAlso A.Length > 0 Then
Console.Write("Enter the name of the File to Save To (example: `Matrix.txt`): ")
Dim response As String = Console.ReadLine()
Dim fullPathFileName As String = System.IO.Path.Combine(Environment.CurrentDirectory, response)
Try
If System.IO.File.Exists(fullPathFileName) Then
Console.WriteLine("")
Console.WriteLine("There is already a file at:")
Console.WriteLine(fullPathFileName)
Console.WriteLine("")
Console.Write("Would you like to overwrite it? Enter 'Y' or 'YES' to confirm: ")
response = Console.ReadLine.ToUpper
If response <> "Y" AndAlso response <> "YES" Then
Exit Sub
End If
End If
Using fs As New System.IO.FileStream(fullPathFileName, IO.FileMode.OpenOrCreate)
fs.SetLength(0) ' reset file length to 0 in case we are overwriting an existing file
Using sw As New System.IO.StreamWriter(fs)
Dim line As New System.Text.StringBuilder
sw.WriteLine((A.GetUpperBound(0) + 1).ToString()) ' size of array in first line
For i As Integer = 0 To A.GetUpperBound(0)
line.Clear()
For j As Integer = 0 To A.GetUpperBound(1)
line.Append(A(i, j).ToString() & " ")
Next
sw.WriteLine(line.ToString().Trim()) ' output each row to the file
Next
End Using
End Using
Console.WriteLine("")
Console.WriteLine("Matrix successfully saved to:")
Console.WriteLine(fullPathFileName)
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine("Error Saving Matrix!")
Console.WriteLine("Error: " & ex.Message)
End Try
Else
Console.WriteLine("The Matrix is empty!")
End If
End Sub
Public Sub LoadMatrix()
Console.Write("Enter the name of the File to Load From (example: `Matrix.txt`): ")
Dim response As String = Console.ReadLine()
Try
Dim A2(,) As Integer
Dim line As String
Dim value As Integer
Dim values() As String
Dim arraySize As Integer
Dim fullPathFileName As String = System.IO.Path.Combine(Environment.CurrentDirectory, response)
Using sr As New System.IO.StreamReader(fullPathFileName)
line = sr.ReadLine ' get matrix size and convert it to an int
If Integer.TryParse(line, value) Then
arraySize = value
ReDim A2(arraySize - 1, arraySize - 1)
For row As Integer = 0 To arraySize - 1
values = sr.ReadLine().Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
If values.Length = arraySize Then
For col As Integer = 0 To arraySize - 1
If Integer.TryParse(values(col).Trim, value) Then
A2(row, col) = value
Else
Console.WriteLine("")
Console.WriteLine("Invalid Element in file!")
Exit Sub
End If
Next
Else
Console.WriteLine("")
Console.WriteLine("Invalid Row Size in file!")
Exit Sub
End If
Next
Else
Console.WriteLine("")
Console.WriteLine("Invalid Matrix Size in first line of file!")
Exit Sub
End If
End Using
A = A2
Console.WriteLine("")
Console.WriteLine("Matrix successfully loaded from:")
Console.WriteLine(fullPathFileName)
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine("Error Loading Matrix!")
Console.WriteLine("Error: " & ex.Message)
End Try
End Sub
End Module

Pasting data into a DataGridView vb.net

So this morning I ran into a wall:
Using this Code I randomly get another row to show up when i paste my data.
It is meant to receive values ranging from 1 to 99999
So when i copy this:
And paste it into the Program this happens:
Private Sub DataGridView101_KeyDown(sender As Object, e As KeyEventArgs) Handles DataGridView101.KeyDown
If e.Control And
e.KeyCode = Keys.V Then
IsCopyPaste = True
Dim _ClipboardRows As String() = System.Windows.Forms.Clipboard.GetText().Split({System.Environment.NewLine}, StringSplitOptions.None)
Me.DataGridView101.BeginEdit(True)
For Each _ClipboardRow As String In _ClipboardRows
If _ClipboardRow <> "" Then
Dim _CellL As String = ""
Dim _CellR As String = ""
For Each _ClipboardColumn As String In _ClipboardRow.Split(System.Convert.ToChar(vbTab))
If _CellL = "" Then
_CellL = _ClipboardColumn
Else
If _CellR = "" Then
_CellR = _ClipboardColumn
End If
End If
Next
Dim _DataRow As System.Data.DataRow = (CType(Me.DataGridView101.DataSource, System.Data.DataTable)).NewRow()
_DataRow("1") = _CellL
_DataRow("2") = _CellR
CType(Me.DataGridView101.DataSource, System.Data.DataTable).Rows.Add(_DataRow)
End If
Next
Me.DataGridView101.EndEdit()
CType(Me.DataGridView101.DataSource, System.Data.DataTable).AcceptChanges()
IsCopyPaste = False
End If
End Sub
Below is my solution for that. You must call the functions from your event. In my application I need to decide allow pasting or not in the PasteUnboundRecords sub, which is controlled by the Allowed boolen
Public Sub CopyRows(MyDataGridView As DataGridView)
Dim d As DataObject = MyDataGridview.GetClipboardContent()
Try
Clipboard.SetDataObject(d)
Catch
MessageBox.Show("Text not copied, null value")
End Try
End Sub
Sub PasteUnboundRecords(MyDataGridView As DataGridView)
Dim Allowed As Boolean
Dim OriginLines As String() = Clipboard.GetText(TextDataFormat.Text).Split(New String(0) {vbCr & vbLf}, StringSplitOptions.None)
Dim Xo As Integer = SelectedAreaMinColumn(MyDataGridview)
Dim Yo As Integer = SelectedAreaMinRow(MyDataGridview)
Dim X As Integer
Dim Y As Integer
Dim i As Integer
Dim j As Integer
Dim ii As Integer
Dim jj As Integer = 0
Dim m1 As Integer
Dim n1 As Integer = OriginLines.Length
Dim m2 As Integer = SelectedAreaColumns(MyDataGridView)
Dim n2 As Integer = SelectedAreaRows(MyDataGridview)
Dim m2Max As Integer = MyDataGridview.Columns.Count
Dim n2Max As Integer = MyDataGridview.Rows.Count
For j = 0 To Math.Max(n1-1, n2-1)
Y = Yo + j
If Y = n2Max Then Exit For
If j-jj*n1 = n1 Then jj = jj+1
Dim OriginValue As String() = OriginLines(j-jj*n1).Split(New String(0) {vbTab}, StringSplitOptions.None)
m1 = OriginValue.Length
ii = 0
For i = 0 To Math.Max(m1-1, m2-1)
X = Xo + i
If X = m2Max Then Exit For
If i-ii*m1 = m1 Then ii = ii+1
If X > 0 Then 'Avoid pasting in first column containing codes
If Y = 0 Then 'Avoid first line
Allowed = True
Else 'Check DataValidatios
If DataValidations(OriginValue(i-ii*m1), X) = "OK" Then
Allowed = True
Else
Allowed = False
End If
End If
'Avoid pasting in Readonly columns
If MyDataGridview.Rows(Y).Cells(X).ReadOnly Then
Allowed = False
End If
If Allowed Then
MyDataGridview.Rows(Y).Cells(X).Value = OriginValue(i-ii*m1)
End If
End If
End If
Next i
Next j
End Sub
Private Function SelectedAreaMinRow(MyDataGridView As DataGridView) As Integer
Dim minRowIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minRowIndex = MyDataGridView.SelectedCells.Item(i).RowIndex
End If
minRowIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).RowIndex, minRowIndex)
Next i
Return minRowIndex
End Function
Private Function SelectedAreaMinColumn(MyDataGridView As DataGridView) As Integer
Dim minColumnIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minColumnIndex = MyDataGridView.SelectedCells.Item(i).ColumnIndex
End If
minColumnIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).ColumnIndex, minColumnIndex)
Next i
Return minColumnIndex
End Function
Private Function SelectedAreaRows(MyDataGridView As DataGridView) As Integer
Dim minRowIndex As Integer
Dim MaxRowIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minRowIndex = MyDataGridView.SelectedCells.Item(i).RowIndex
MaxRowIndex = MyDataGridView.SelectedCells.Item(i).RowIndex
End If
minRowIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).RowIndex, minRowIndex)
MaxRowIndex = Math.Max(MyDataGridView.SelectedCells.Item(i).RowIndex, MaxRowIndex)
Next i
Return MaxRowIndex-minRowIndex+1
End Function
Private Function SelectedAreaColumns(MyDataGridView As DataGridView) As Integer
Dim minColumnIndex As Integer
Dim MaxColumnIndex As Integer
For i As Integer = 0 To MyDataGridView.SelectedCells.Count - 1
If i = 0 Then
minColumnIndex = MyDataGridView.SelectedCells.Item(i).ColumnIndex
MaxColumnIndex = MyDataGridView.SelectedCells.Item(i).ColumnIndex
End If
minColumnIndex = Math.Min(MyDataGridView.SelectedCells.Item(i).ColumnIndex, minColumnIndex)
MaxColumnIndex = Math.Max(MyDataGridView.SelectedCells.Item(i).ColumnIndex, MaxColumnIndex)
Next i
Return MaxColumnIndex-minColumnIndex+1
End Function

Pictures wont become visible

So today in my Computer Programming Class, we created a project called CaseStudy. I saw a way to make the program have more replay value. I decided to morph the code and interface to be like a Hangman game. I've got the limbs to appear, but only after clicking Ok on the messageBox.
I'm wondering if anyone has a way to make these limbs appear in real time.
Here is the important code:
Dim SECRET_WORD As String = newSecretWord
Const FLAG As Char = "!"
Const GUESS_PROMPT As String = "Enter a letter or " & FLAG & " to guess word:"
Dim numGuesses As Integer = 0
Dim letterGuess As Char
Dim wordGuess As String
Dim tempWord As String
Dim endGame As Boolean
Dim wordGuessedSoFar As String = ""
Dim lenght As Integer = SECRET_WORD.Length
wordGuessedSoFar = wordGuessedSoFar.PadLeft(lenght, "_")
Me.lblSecretWord.Text = wordGuessedSoFar
Dim tempLetterGuess = InputBox(GUESS_PROMPT, Me.Text)
If tempLetterGuess = Nothing Then
endGame = True
Else
letterGuess = tempLetterGuess
End If
Do While letterGuess <> FLAG And wordGuessedSoFar <> SECRET_WORD And Not endGame
numGuesses += 1
For letterPos As Integer = 0 To SECRET_WORD.Length - 1
If SECRET_WORD.Chars(letterPos) = Char.ToUpper(letterGuess) Then
tempWord = wordGuessedSoFar.Remove(letterPos, 1)
wordGuessedSoFar = tempWord.Insert(letterPos, Char.ToUpper(letterGuess))
Me.lblSecretWord.Text = wordGuessedSoFar
End If
Next letterPos
If wordGuessedSoFar <> SECRET_WORD Then
tempLetterGuess = InputBox(GUESS_PROMPT, Me.Text)
If tempLetterGuess = Nothing Then
endGame = True
Else
letterGuess = tempLetterGuess
End If
End If
Loop
If wordGuessedSoFar = SECRET_WORD Then
MessageBox.Show("You guessed it in " & numGuesses & " guesses!")
ElseIf letterGuess = FLAG Then
wordGuess = InputBox("Enter a word: ", Me.Text)
If wordGuess.ToUpper = SECRET_WORD Then
MessageBox.Show("You guessed it in " & numGuesses & " guesses!")
Me.lblSecretWord.Text = SECRET_WORD
Else
MessageBox.Show("Sorry, you lose.")
End If
Else
MessageBox.Show("Game over.")
lblSecretWord.Text = Nothing
End If
Dim place As Integer = SECRET_WORD.Length - 1
If tempLetterGuess <> SECRET_WORD.Chars(place) Then
numWrong += 1
End If
If numWrong = 1 Then
picHead.Visible = True
End If
If numWrong = 2 Then
picBody.Visible = True
End If
End Sub
End Class
I can take any other pictures if you'd like.
If I'm understanding you right, you want to show your "pictures" before the user sees the message. If so, you need to move the following code to an area just before your MessageBox and just after the InputBox:
Dim place As Integer = SECRET_WORD.Length - 1
If tempLetterGuess <> SECRET_WORD.Chars(place) Then
numWrong += 1
End If
If numWrong = 1 Then
picHead.Visible = True
End If
If numWrong = 2 Then
picBody.Visible = True
End If

Hangman vb.net only first letter showing

Basically I generate a random word for example
"Tree" and when I press the T button it changes the label into a T but then when I choose R it doesnt show, can someone else see what i've done wrong?
here is my code
Sub GuessLetter(ByVal LetterGuess As String)
Dim strGuessedSoFar As String = Lbltempword.Text
Dim LengthOfSecretWord As Integer
LengthOfSecretWord = secret.Length - 1
tempWord = ""
Dim letterPosition As Integer
For letterPosition = 0 To LengthOfSecretWord
If secret.Substring(letterPosition, 1) = LetterGuess Then
tempWord = tempWord & LetterGuess
Else
tempWord = tempWord & Lbltempword.Text.Substring(letterPosition, 1)
End If
Next
Lbltempword.Text = tempWord
If Lbltempword.Text = secret Then 'YOU WIN
DisableButtons()
BtnStart.Enabled = True
MsgBox("YOU WIN")
End If
If Lbltempword.Text = strGuessedSoFar Then
NumWrong = NumWrong + 1
End If
DisplayHangman(NumWrong)
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
randomword()
MsgBox(secret)
EnableButtons()
BtnStart.Enabled = False
'Load up the temp word label with dashes
Secret_Word = secret
LoadLabelDisplay()
NumWrong = 0
DisplayHangman(NumWrong)
End Sub
Sub LoadLabelDisplay()
Lbltempword.Text = ""
Dim LengthOfSecretWord As Integer
LengthOfSecretWord = secret.Length - 1
Dim LetterPosition As Integer
For LetterPosition = 0 To LengthOfSecretWord
Lbltempword.Text = Lbltempword.Text & "-"
Next
End Sub
I also generate the random words by doing this.
Sub randomword()
Dim RAND(16)
Dim rng As New System.Random()
For i = 0 To 16
RAND(0) = "Tree"
RAND(1) = "Star"
RAND(2) = "Jesus"
RAND(3) = "Present"
RAND(4) = "advent"
RAND(5) = "Calender"
RAND(6) = "Jinglebell"
RAND(7) = "skint"
RAND(8) = "lapland"
RAND(9) = "Santa"
RAND(10) = "raindeer"
RAND(11) = "Cookies"
RAND(12) = "Milk"
RAND(13) = "nothing"
RAND(14) = "play"
RAND(15) = "sack"
Next
secret = RAND(rng.Next(RAND.Count()))
End Sub

Using EF model database not Updating with updateModel

MVC 3, VB.NET, RAZOR app, using EF. I am having an issue in my post function with the database not updating at all... Using a break at db.savechanges() I look at the variable and all of the correct information is contained in the UpdateModel( ) part. But no dice the code executes and returns no errors so all looks fine but when I look at the database table it has not been changed at all, all of the old values are still present.. Function is as follows:
<AcceptVerbs(HttpVerbs.Post)>
Function EditCourse(ByVal _eCourse As cours) As ActionResult
Dim id As Integer = _eCourse.course_id
Dim _filename As String = String.Empty
Dim _guid As String = String.Empty
Dim _count As Integer = 0
Dim _courseFiles As cours = db.courses.Where(Function(f) f.course_ref = _eCourse.course_ref).First
Dim _file1 As String = _courseFiles.handoutFile1
Dim _file2 As String = _courseFiles.handoutFile2
Dim _file3 As String = _courseFiles.handoutFile3
Dim _file4 As String = _courseFiles.handoutFile4
Dim _file5 As String = _courseFiles.handoutFile5
Dim _file6 As String = _courseFiles.handoutFile6
Dim _file7 As String = _courseFiles.handoutFile7
Dim _file8 As String = _courseFiles.handoutFile8
For Each File As String In Request.Files
_count += 1
Dim hpf As HttpPostedFileBase = TryCast(Request.Files(File), HttpPostedFileBase)
If hpf.ContentLength = 0 Then
Continue For
End If
Dim savedfileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + hpf.FileName
hpf.SaveAs(savedfileName)
_filename = hpf.FileName
Select Case _count
Case Is = 1
If Not String.IsNullOrWhiteSpace(_file1) Then
If Not String.Compare(_eCourse.handoutFile1, _file1) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile1) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file1
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile1 = _filename
Case Is = 2
If Not String.IsNullOrWhiteSpace(_file2) Then
If Not String.Compare(_eCourse.handoutFile2, _file2) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile2) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file2
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile2 = _filename
Case Is = 3
If Not String.IsNullOrWhiteSpace(_file3) Then
If Not String.Compare(_eCourse.handoutFile3, _file3) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile3) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file3
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile3 = _filename
Case Is = 4
If Not String.IsNullOrWhiteSpace(_file4) Then
If Not String.Compare(_eCourse.handoutFile4, _file4) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile4) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file4
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile4 = _filename
Case Is = 5
If Not String.IsNullOrWhiteSpace(_file5) Then
If Not String.Compare(_eCourse.handoutFile5, _file5) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile5) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file5
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile5 = _filename
Case Is = 6
If Not String.IsNullOrWhiteSpace(_file6) Then
If Not String.Compare(_eCourse.handoutFile6, _file6) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile6) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file6
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile6 = _filename
Case Is = 7
If Not String.IsNullOrWhiteSpace(_file7) Then
If Not String.Compare(_eCourse.handoutFile7, _file7) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile7) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file7
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile7 = _filename
Case Is = 8
If Not String.IsNullOrWhiteSpace(_file8) Then
If Not String.Compare(_eCourse.handoutFile8, _file8) = 0 AndAlso Not String.IsNullOrWhiteSpace(_eCourse.handoutFile8) Then
Dim FileToDelete As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\CourseHandouts\" + _file8
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
End If
_eCourse.handoutFile8 = _filename
End Select
Next
UpdateModel(_eCourse)
db.SaveChanges()
Return RedirectToAction("CourseIndex")
End Function
Any Ideas on why this is going wrong?????
You aren't attaching your _eCourse to your context so it won't update it.
UpdateModel I don't believe is required here at all as that simply takes your posted form values an assigns to your model which you already have since eCourse is a parameter. Do something like (on phone here sorry)
DB.Entry(_eCourse).State = EntityState.Modified
And then save changes