Iterate through variables using a variable? - vb.net

I'm trying to find a way to iterate through a list of Strings to be displayed in a text box. These Strings are retrieved from a separate class called 'texts'.
The Strings are declared in the 'texts' class as (for ngs1, 2, 3, etc)
Public Shared ngs1 As String = "Text"
This chunk runs when a next button is clicked, the button's purpose being to iterate through the list of texts displayed.
ElseIf firstTimeRun = True Then
welcome += 1
Select Case welcomePages
Case 1
txtDisplay.Text = texts.ngs1
Case 2
txtDisplay.Text = texts.ngs2
Case 3
txtDisplay.Text = texts.ngs3
End Select
I'm wanting to be able to do this without a select case, so that it's essentially
'Pseudo code
ElseIf firstTimeRun = True Then
welcome += 1
txtDisplay.text = texts.ngs(welcome)
I'm not sure how to properly do this, by using a variable in the name of other variables. Any help would be greatly appreciated, thanks!

If you just want to iterate through all this texts, just create a list(of String) or array and add all the ngsX...
As Example:
Dim list as List(Of String)
Dim indexActualShownString as Integer
Then you can just use in your Clicked_Event
txtDisplay.text=list.Items(indexActualShownString) as Integer
indexActualShwonString += 1
But I am not sure if I understand your problem right. And you should also implement a way to reset indexActualShownString, since I dont know what exactly its the purpose of it.

Related

Visual Basic Iterative enabling of Textbox's

Si I'm working on an assignment where I have 10 RadioButtons indicating how many contesters I have, and depending on what I pick between 1 to 10, I need that many of my corresponding TextBoxes to be enabled so I could fill it with names!
Is there a way for me to make a For loop between 1 and the number I picked from the RadioButton and say something like
For i = 0 to Size
{
TextBox&i.Enabled = True
}
Since my TextBoxs are called TextBox1 to TextBox10
I know you can add strings together using &, but how can I do that for an object name?
As of right now I literally have the dumbest way of doing it, which is a click event inside each RadioButton that manually enables the correct number of TextBoxes...
Thank you in advance!
You can iterate over all controls like this:
For Each ctr In Me.Controls
Dim indx As String = ctr.Name
If TypeOf (ctr) Is Textbox Then
' Now compare the name with TextBox&i and do smth
End If
Next
It's not possible to just concatenate a string and use it as an object variable reference like that, but you can search the form's controls by their name property (which is a string) and do it that way. Here's an example:
Private Sub EnableTextBoxes(ByVal Size As Integer)
For i As Integer = 1 To Size
Dim matches() As Control = Me.Controls.Find("Textbox" & i.ToString, True)
If matches IsNot Nothing AndAlso matches.Length = 1 Then matches(0).Enabled = True
Next
End Sub

Find a variable with concatenation

I would like to find a variable with concatenation.
Exemple :
Dim oExcelRangeArray1(0, 0) As Object
Dim oExcelRangeArray2(0, 0) As Object
Dim oExcelRangeArray3(0, 0) As Object
For i As Integer = 1 To 3
oExcelRangeArray & i = xl.Range("A1:Z400").Value
Next
but oExcelRangeArray & i doesn't work.
Thank you
For the extent of my knowledge, there is no way to achieve what you are trying to do directly, because oExcelRangeArray & i will not be evaluated as a separate step before the variable assignment happens.
In my mind you have two choices:
Assign each variable individually,
oExcelRangeArray1 = x1.Range("A1:Z400").Value
oExcelRangeArray2 = x1.Range("A1:Z400").Value
oExcelRangeArray3 = x1.Range("A1:Z400").Value
oExcelRangeArray4 = x1.Range("A1:Z400").Value
Or, add each array to a list, and iterate through it,
Dim oExcelRangeArrayList As New List(Of Object)
oExcelRangeArrayList.Add(oExcelRangeArray1)
oExcelRangeArrayList.Add(oExcelRangeArray2)
oExcelRangeArrayList.Add(oExcelRangeArray3)
oExcelRangeArrayList.Add(oExcelRangeArray4)
For i As Integer = 0 To 3
oExcelRangeArrayList(i) = x1.Range("A1:Z400").Value
Next
[Note: Writing this freehand without checking it, code may not be verbatim; hopefully you get the concept. Corrections welcome.]

Refer to forms controls using variable

I've seen many threads on this, but I'm pretty much lost.
For the example below, I have 3 ComboBoxes (cbx_example0, cbx_example1, cbx_example2) located on three TabPages (index 0, 1, 2), respectively. I'd like set the value of the variable myVariable based on the ComboBox on the selected TabPage.
However, I can't seem to figure out how to refer to the ComboBox using a variable. It seems like it should be straightforward, but I guess not. No matter what I do, I get a NullReferenceException.
Function to get TabPage Index number (returns 0 for this example)
Function getTabIndex()
Dim currentTabIndex As Int32 = frm_Main.TabControl1.SelectedIndex
Return currentTabIndex
End Function
Attempt 1 to refer to ComboBox with variable
Dim myVariable As String
Dim i As Integer = getTabIndex
myVariable = frm_Main.Controls("cbx_example" & i).Text
Attempt 2 to refer to ComboBox with variable
Dim cbx_example0 As New ComboBox
Dim i As Integer = getTabIndex()
Dim name As String = "cbx_example" & i.ToString
cbx_example = frm_Main.Controls.Item(name)
myVariable = cbx_example.Text
Your problem is that you think that your cbo is located on the form, while in reality it is on the tabpage. Instead of
cbx_example = frm_Main.Controls.Item(name)
use (for example)
cbx_example = frm_Main.TabPage1.Controls.Item(name)
Keep in mind that your combo is probably not on tab itself but on the tabpage
On another note, I see no need for getTabIndex(). And another way to get any control within hierarchy of your form is to use
form.Controls.Find(key, searchAllChildren)

Error Reading string into array

I'm in the process of creating a tile based game. This game requires a method to load a text file and write the numbers between the delimiter "-", to a multidimensional array. However, an error message "object not set to an instance occurs.
'Load map
Public Sub LoadMap(ByVal URI As String)
Using reader As New System.IO.StreamReader(URI)
For x As Integer = 0 To 13
Dim line = reader.ReadLine()
Dim tokens() As String = line.Split("-")
'adds values to multidimensional array
For y As Integer = 0 To 16
Me.map(x, y) = Integer.Parse(tokens(y))
Next y
Next x
End Using
End Sub
Example map - numbers represent image id's
2-2-2-0-0-0-0-0-0-0-0-3-3-5-5-5-5
2-2-2-0-0-0-0-0-0-0-0-3-3-5-5-5-5
2-2-2-0-0-0-0-0-0-0-0-3-3-2-2-2-5
2-2-2-0-0-0-0-0-0-0-0-3-3-2-2-2-5
2-2-2-0-0-0-0-0-0-0-0-3-3-2-2-2-5
0-0-0-0-0-0-0-0-0-0-0-3-3-2-2-2-5
3-3-3-3-3-3-3-3-3-3-3-3-3-3-3-3-3
4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2
4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2
4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2
4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2
4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2
4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2
4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2
I can't seem to establish the problem. Thanks in advance...
Always use Option Strict On! (Your code shouldn’t even compile, you need to parse the input integers, or your map stores strings, which is equally as bad since you logically store numbers.)
Name your variables properly.
Omit vacuous comments. Only comment things that aren’t obvious from the code.
Don’t hard-code magic numbers (what’s 11? 8?)
Don’t declare variables before initialising. Declare on first use.
The outer loop in your code makes no sense.
Don’t close streams manually, always use a Using block to ensure the program still works in the face of exceptions.
Initialise map.
Which leaves us with:
Public Sub LoadMap(ByVal URI As String)
Const MapHeight As Integer = 12
Const MapWidth As Integer = 9
Me.map = New Integer(MapHeight, MapWidth) { }
Using reader As New System.IO.StreamReader(URI)
For x As Integer = 0 To MapHeight - 1
Dim line = reader.ReadLine()
Dim tokens() As String = line.Split("-")
For y As Integer = 0 To MapWidth - 1
Me.map(x, y) = Integer.Parse(tokens(y))
Next y
Next x
End Using
End Sub
Bonus: Check for errors: what if the map doesn’t have the predefined width/height? Why hard-code this at all?
osRead.ReadLine() returns Nothing if the end of the input stream is reached. You call Peek to see if you're at the end of the input, but then, you proceed to read 12 lines without checking if you're at the end of the input in-between. If you have less than 12 more lines, you'll get the error you mentionned on temp.Split("-"), because temp will have a value of Nothing, so you can't call methods on it.
Also, just noticed something... your Map is 11x8, but you're reading 12 lines, and going through 9 values, you probably want to do:
For x As Integer = 0 To 10
or
For x As Integer = 1 To 11
Same thing for your other loop.
If temp is null (Nothing) in VB.Net, then you can't call methods on it.
Do a check for Nothing before attempting to do anything with the value.
So Just to be sure you have updated your code to look something like this:
If temp IsNot Nothing
'tempLine stores the split read line
Dim tempLine() As String
'splits readline into - ERROR Not set to an instance
tempLine = temp.Split("-")
'adds values to multidimensional array
For y As Integer = 0 To 8
Me.map(x, y) = tempLine(y)
Next y
End If
And you are STILL getting the null reference exeption?
also make sure that your StreamReader is properly initialized... if the initialization fails (perhaps because of a bad URI) then attempting to call osRead.peek() will throw the "object not set to an instance" error.

im having syntax issues pulling data from 6 text boxes with identical names (other than a number at the end) in a for loop

I have 6 different text boxes with similar names:
txtBox1, txtBox2....txtBox6
I also have an array:
dim intValue (0 to 5) as Integer
Now I want to use a for loop to assign the value in each text box to a corresponding space in the array, concatenating the value of the loop counter with the string "txtBox" and retrieving the data using the .text method.
here is my code:
For count As Integer = 0 To 5
Dim strCount As String = count
Dim strTxtBox As String = "txtBox" & strCount
intValues(count) = Convert.toInt32(strTxtBox.Text)
Next
the issue is that the string name doesn't point to txtBox1, txtBox 2 etc.
Thanks in advance for the help.
If you want to access the control name, you have to use the property "Name".
You should try something like that:
For i As Integer = 0 To 5
For Each c As Control In Controls
If c.Name = "txtBox" & i Then
intValue(i) = Convert.ToInt32(c.Text)
End If
Next
Next i
The above code is just an example, but it should work for you.
Anyway you can write a better code checking the type of the control or maybe using a different loop logic, but the basic idea is that if you want to use in your code the name od the control you have to use the NAME property.
strTxtBox is a string, nothing more. You cannot refer to control names by String without special code. Rather than go down that path, I'd create an array and populate it with text boxes:
Dim txtBoxes As TextBox() = {txtBox1, txtBox2, txtBox3, txtBox4, txtBox5, txtBox6}
Dim intValues As Integer(0 To 5)
For count As Integer = 0 To 5
intValues(count) = Convert.ToInt32(txtBoxes(count).Text)
Next
The easiest way is to iterate through the contents of Controls to find the textboxes. You can either:
Use the .Tag property to label textboxes to identify them, or as the other answer points out, use the .Name property.
If you have a lot of other controls on the form, and they may not be in order, you could also check each control to see if it's a textbox. Assume they are in reverse order, as the Controls array goes from end to beginning.
Dim nums() As Integer = {10, 20, 30, 40, 50, 60}
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeOf (ctrl) Is TextBox Then
ctrl.Text = nums(Val(ctrl.Name(ctrl.Name.Length - 1)) - 1)
End If
Next
You could also instantiate an array of textboxes programmatically, but you'd have to set all of the placement, etc. by hand.
As I commented on the answer below, you may need to cast the ctrl to a System.Web.UI.Control to access the .Name, using DirectCast.