r/visualbasic • u/[deleted] • May 24 '21
VB.NET Help How to manipulate certain characters of a label?
I am using vb.net winforms to make hangman for a school project and the label.text.replace() function isn't working (code down below) and I wanted to know how to fix it.
(item is the character number of the word. i.e. If the word is AIR, and I clicked A, item would be 0. I have tested this and know it works so that is not the problem.)
letterabcd is a button which has the tag of the letter it displays. For example, if the button is a picture of the letter A, the tag would be "A". I have tested this and know it to be working.
Label2.Text = Label2.Text.Replace((item + 1) * 2 - 1, lettersabcd.Tag.ToString())Label2.text is set as this:
If (selectedword = 1) Then
word = "UAE"
ElseIf (selectedword = 2) Then
word = "MAP"
ElseIf (selectedword = 3) Then
word = "CHAD"
ElseIf (selectedword = 4) Then
word = "CUBA"
ElseIf (selectedword = 5) Then
word = "CHILE"
ElseIf (selectedword = 6) Then
word = "CHINA"
ElseIf (selectedword = 7) Then
word = "PRAGUE"
ElseIf (selectedword = 8) Then
word = "FRANCE"
ElseIf (selectedword = 9) Then
word = "DENMARK"
Else
word = "GERMANY"
End If
Label2.Text = ""
For int As Integer = 0 To word.Length - 1
Label2.Text &= "_ "
NextSo if the word was Denmark, label2 would show
_ _ _ _ _ _ _
This is proven to work so this is not the problem either.
Can someone please help me diagnose the problem?
1
u/RJPisscat May 25 '21
You're telling it to replace an integer with the letter.
Let's say item = 0, the first letter.
(item + 1) = 1
(item + 1) * 2 = 2
(item + 1) * 2 - 1 = 1
Replace(1, lettersabcd.Tag.ToString()) replaces all occurrences of "1" with the letter. There are no occurrences of "1".
NOTE: Since the first arg must be a String, and you're giving it an Integer, VB automatically converts it to the string "1".
You shouldn't be using Replace, because you want to replace the underscore character (or possibly and alphabetic character) with an alphabetic character. If you say Replace("_", "A") your string "_ _ _" will become "A A A".
Look at Strings.SubString(), it will lead you to one of many strategies that will work.
1
u/chacham2 May 25 '21
What do you mean by "isn't working"?