Will you please help me in my migration to VB.NET from VB 6.0? [duplicate] - arrays

This question already has answers here:
Control array in VB.NET
(3 answers)
Closed 8 years ago.
I just read a certain article about the control arrays of VB6 not present in VB.NET and rather, became a "collection" or something.... (http://visualbasic.about.com/od/usingvbnet/l/bldykctrlarraya.htm)
Now, I'm planning to learn VB.NET and accept it as whole new language.
So, as a "few steps" for me to migrate, here is my code from VB6:
Private Sub Command1_Click()
For i = 0 to 9
Command2(i).Caption = i
Next i
End Sub
Private Sub Command2_Click(Index as Integer)
Label1.Caption = Label1.Caption + Index
End Sub
I wonder if you get what my program is? Let's just say it's a certain number pad program. I'll explain what this program does, at least for now...
As you can see, I have 12... controls? (I'm sorry, I'm still a little bit new in terms of programming)... Yeh, 12 of them... 11 buttons and 1 Label. That 1 button, Command1, will give the captions of my other 10 buttons Command2(Index). And when Command2(Index) is pressed, Label1's current caption will be concatenated by Command2(Index)'s Index... (It's like a calculator, let's skip this now)
So, will you teach me a version/translation of this in VB.NET? :) Thanks!

Just Add 12 regular buttons onto your form Button1 - Button12
Then create a list to hold a reference to these:
Private _buttonList As New List(Of Button)
Add your buttons to the list on Form_Load:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_buttonList.Add(Button1)
_buttonList.Add(Button2)
_buttonList.Add(Button3)
'etc.
End Sub
Then you can use the list to access your buttons by (zero based) index:
_buttonList(4).Text = "foo"

Related

VB Array IndexOf error (Noughts and Crosses Game)

Being new to programming and having it introduced to me through my course I've been doing tasks in and out of College in Visual Basic using Visual Studio to make games and other little applications. However in my most recent project i've experienced a problem in one of my arrays I have never come across before. The specific error im getting comes up with this when highlighted:
Data type(s) of the type parameter(s) in method 'Public Shared Overloads Function IndexOf(Of T)(array As T(), value As T) As Integer' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.
I have all the arrays (18, for 9 different buttons each containing a question and an answer variant) running in form load as it was the only way I could get the arrays to work with a randomiser and show the question in the button. Then the array index is being found and created in the submit answer button. I'll give some snippets for further context below from various points where the array is being referenced :)
I created this to make the string global but I have an inkling this is wrong?
Public Class Form3
Public QBox1 As String
Public QBoxA1 As String
This is where the arrays are and how i've structured them
Public Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BOX 1 (TOP LEFT)
Dim QBox1() As String = {"√81", "4x6", "16/4", "21+18", "81-23"}
Dim QBoxA1() As Integer = {"9", "24", "4", "39", "58"}
And finally this is within the submit answer button where the error is
If QBoxA1.Contains(txt_AnswerAttempt.Text) Then
Dim question_index = Array.IndexOf(QBox1, btn_Q1.Text)
Dim answer_index = Array.IndexOf(QBoxA1, answerAttemptDisplay.Text)
If question_index = answer_index Then
MsgBox("Correct Answer!")
Else
MsgBox("Wrong Answer!")
End If
End If
Sorry for information overload, I wanted to be thorough right off the bat! Cheers for giving this a read if you made it to the end xD
Your declaration isn't right. Since you want an array, don't declare it as a single string. It should be:
Public QBox1() As String
then in the load event, don't re-declare it with a Dim statement. Just re-populate it:
QBox1 = {"√81", "4x6", "16/4", "21+18", "81-23"}

Manipulating Array After Pulling From Text File

I've been thoroughly combing StackOverflow and other sources for the answers to these problems, and have not been able to find a solution that would work cohesively with the steps I need to accomplish.
Things I need to do:
Create an array from a text file and display in a listbox (this is done and works)
Have user fill in a text box, click a button, and the array is searched for anything matching the text box's value
Have the results of the search displayed in a separate listbox
Here's what I've got so far, and it's fairly hacked together, so if there's anything that can be improved, naturally, I'd be all for that.
`
Public Class Form1
Dim lblName As Object
Public colleges As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim colleges() As String = IO.File.ReadAllLines("Colleges.txt")
ListBoxCollege.Items.AddRange(colleges)
End Sub
Private Sub btnSearchGo_Click(sender As Object, e As EventArgs) Handles btnSearchGo.Click
Dim n As Integer, college As String
college = txtCollegeSearchUserInput.Text
n = Array.IndexOf(colleges(), college)
If n <> 1 Then
[[Needs to output into new listbox, preferably here]]
End If
End Sub
If there's anything else needed from VB, I can provide if necessary!
In your case you can do something like this
For i As Integer = 0 To ListBoxCollege.Items.Count -1
If ListBoxCollege.Items(i).ToString().IndexOf(college, StringComparison.OrdinalIgnoreCase) > -1 Then
findList.Items.Add(ListBoxCollege.Items(i))
End If
Next
The difference here - you calling IndexOf on array and I call it for each item in list. Therefore I return all matches, while you only the first one
This is little bit limited in search criteria. You could use regex as well for wild cards etc. Or you store your data (colleges) in System.Data.DataTable, and you would be able to run Sql Select queries on it almost like in database.

Control Array Examples Needed for Visual Studio 2013

I know control arrays don't actually exist anymore, but I need something I can relate to my code. I'm making a shopping list game with a grid of 32 tiles that flip when clicked. They are actually PictureBoxes called pbxTile1 - pbxTile32. I sense you already know what I'm going to say.
A sample of my code:
Private Sub pbxTile1_Click(sender As Object, e As EventArgs) Handles pbxTile1.Click
If TileFlag(1) = 0 Then Exit Sub
My.Computer.Audio.Play(My.Resources.Tile_Flip, AudioPlayMode.Background) : Application.DoEvents()
Me.pbxTile1.BackgroundImageLayout = ImageLayout.Stretch
Me.pbxTile1.BackgroundImage = My.Resources.FLIP01 : Application.DoEvents() : System.Threading.Thread.Sleep(50)
Me.pbxTile1.BackgroundImage = My.Resources.FLIP02 : Application.DoEvents() : System.Threading.Thread.Sleep(50)
Me.pbxTile1.BackgroundImage = My.Resources.FLIP03 : Application.DoEvents() : System.Threading.Thread.Sleep(50)
Dim GroceryValue = TileItem(1)
Call Get_Grocery(GroceryValue)
Me.pbxTile1.BackgroundImageLayout = ImageLayout.None
Me.pbxTile1.BackgroundImage = My.Resources.ResourceManager.GetObject(GroceryResource) : Application.DoEvents()
You can see my problem - this is a fraction of the subroutine, which I need to recreate 32 times. But I'm sure one of you bright lads can come up with something to make it much less painful for me! I've seen tagging, and lists, and indexing - but not sure how to apply it, which is best, and need some examples please!
It's ok, I've found it! My word it works perfectly:
I didn't realise that Event Handlers can handle multiple Controls!
Instead of duplicating my code (32 times!) I just changed the Sub to:
Private Sub pbxTile_Click(ByVal sender As Object, e As System.EventArgs) Handles pbxTile1.Click, pbxTile2.Click, pbxTile3.Click, pbxTile4.Click, pbxTile5.Click, pbxTile6.Click, _
pbxTile7.Click, pbxTile8.Click, pbxTile9.Click, pbxTile10.Click, pbxTile11.Click, pbxTile12.Click, pbxTile13.Click, pbxTile14.Click, pbxTile15.Click, pbxTile16.Click, _
pbxTile17.Click, pbxTile18.Click, pbxTile19.Click, pbxTile20.Click, pbxTile21.Click, pbxTile22.Click, pbxTile23.Click, pbxTile24.Click, pbxTile25.Click, pbxTile26.Click, _
pbxTile27.Click, pbxTile28.Click, pbxTile29.Click, pbxTile30.Click, pbxTile31.Click, pbxTile32.Click
So basically if any of the 32 boxes are clicked, it calls the same Sub. And to differentiate between each PictureBox (this is the bit I was REALLY stuck on) I used DirectCast:
For z = 1 To 32
If DirectCast(sender, PictureBox).Name = "pbxTile" & z And TileFlag(z) = 0 Then Exit Sub
Next
I'm not sure if this is the most streamlined way, but it certainly works a treat, and saved me a bunch of code I didn't need!

Reading from a list in a text file, ripping certain a line and showing in listbox, Visual studio 2010

I'm creating a barcode scanning program in visual studio 2010 using vb.
I have come on pretty far, but have seemed to get stuck at this little problem.
I have a text file saved and a data in it displayed like this:
0001#Unsmoked Middle Bacon
0002#Smoked Middle bacon
0003#Unsmoked Bits
0004#Smoked Bits
0005#Unsmoked Back
0006#Smoked Back
0007#Unsmoked Streaky
0008#Smoked Streaky
I have no problem reading and splitting the strings with #, and I can populate 2 listboxes, 1 displaying the 4 digit code, and the other the product name. (this was just a test scenario)
What i really want to do, is search the file for a variable that is a user inputed number such as "0004" and this would display back to me "smoked bits".
I think i am wanting to read down line by line, until it hits the right number, then read across maybe using a substr? You guys could probably help me alot here.
While Not sreader.EndOfStream
lineIn = sreader.ReadLine()
Dim elements() As String = Nothing
elements = lineIn.Split("#")
lstProdTest.Items.Add(elements(0))
lstProdName.Items.Add(elements(1))
PLUnumber(index) = elements(0)
itemName(index) = elements(1)
numProds = numProds + 1
index = index + 1
End While
As Origin says, providing this file isnt so large as to consume too much memory, reading the data once is the way to go:
Private _barcodes As Dictionary(Of Integer, String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'EDIT forgot to initialize _barcodes:
_barcodes = New Dictionary(Of Integer, String)
For Each line In IO.File.ReadAllLines("c:\path\to\file.txt")
Dim data = line.Split("#"c)
_barcodes.Add(CInt(data(0)), data(1))
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim input As String = InputBox("type the barcode to test, eg 0004:")
Dim key As Integer = CInt(input)
'if you entered 0004 then this will display Smoked Bits
If _barcodes.ContainsKey(key) Then
MessageBox.Show(_barcodes(key))
Else
MessageBox.Show("Key not found")
End If
End Sub
Note this is just a quick example and would require error handling to be added (for missing file, incorrect format of data etc)
If the amount of data is huge then consider a database instead, sqlite would be a simple option
As they say, premature optimization is the root of all evils. Instead of reading your file each time you need an item description, you should read the file in once (at the start of the application), store it in memory (perhaps as a Dictionary(of Integer, String)) and then reference this when trying to get the description for an item.
You could of course go further and create a custom class to store additional information about each entry.

Trouble reading database records into memory variables in VB 2010

I followed an example on stackoverflow about how to read database records into variables. This is the first time doing this and I feel that I'm close but I'm baffled at this point about the problem.
Here is the link I am referring to:
Visual Basic 2010 DataSet
My code is shown below.
Public Class Form1
' DataSet/DataTable variables
Dim testdataDataSet As New DataSet
Dim dttestdataDataTable As New DataTable
Dim datestdataDataAdapter As New Odbc.OdbcDataAdapter
' Variables for retrieved data
' Dim sSpeed As String = ""
' Dim sFuelprice As String = ""
Dim sSpeed As Integer
Dim sFuelprice As Integer
'Connect to the database
''
'Fill DataSet and assign to DataTable
datestdataDataAdapter.Fill(TestdataDataSet , "TestdataDataSet")
dttestdataDataTable = TestdataDataSet.Tables(0)
'Extract data from DataTable
' Rows is the row of the datatable, item is the column
sSpeed = dtTestdataDataTable.Rows(0).Item(0).ToString
sFuelprice = dtTestdataDataTable.Rows(0).Item(1).ToString
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
result.Text = Val(miles.Text) * sSpeed * sFuelprice
End Sub
End Class
Basically, I am getting declaration errors and I don't understand why since the example I was following clearly declared them. I'm connecting to an Access DB called "testdata.mdb" which contains only 1 record with two fields that I want to use throughout the program. The exanple said to dim the variables for each field as strings but this created more dim errors so I made them into integers and remarked out the original dim statements in the meantime (since they're going to be used in calculations.) The dataadapter and datatable variables also are getting flagged for not being declared when they were earlier in the program. I know this must be a simple thing to fix but I'm just not seeing it.
The form is just a simple thing where the user types in a number and a result is produced by using the numbers read in from the database. In short, I want to be able to do simple calculations with a database within a program and the dim statement thing is getting in the way.
If someone can please clarify what I should do, that would be very much appreciated. Thanks!
When you're trying to learn new technology, it's usually best to work from the outside in. The "outside-most" object in your case seems to be an OdbcConnection object.
Public Class Form1
Const connectionString as String = "Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\bin\Northwind.mdb"
Dim connection As New OdbcConnection(connectionString)
connection.Open()
connection.Close()
end Class
Resolve errors at that level first. Then add a declaration for the data adapter--only for the data adapter--and resolve any errors with that. Repeat until you finish your class.
See OdbcConnectionString, and refer to the connection string web site if you need to.
I apologize for the delay in writing the answer to close off this question and sum it up.
In my case, it dataset is a one row database called testdata and contains 20 fields.
The solution that worked is as follows:
Immediately after the form1_load event, the variables can be immediately written after the dataadapter line:
Me.TestdataTableAdapter.Fill(Me.fooDataSet.testdata)
speed = Me.fooDataSet.testdata(0).speed
fuelprice = Me.fooDataSet.testdata(0).fuelprice
mpg = Me.fooDataSet.testdata(0).mpg
Then just DIM the variables to whatever you want them to be (in this case, speed is an integer, fuelprice is a decimal and MPG is a decimal) right after the PUBLIC CLASS statement at the top of your form's code.
You can then manipulate the variables in calculations after a button click as such:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
fuelcost = CDec((miles.Text/ mpg) * fuelprice)
txtfuelcost.Text = fuelcost.ToString
End Sub
Thank you all for your responses!

Resources