Manipulating Array After Pulling From Text File - arrays

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.

Related

Error reading JArray from JsonReader VB.net

where does it go wrong?
my coding
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.Net
Public Class DigiposAJA
Private Sub CekPaket()
Dim json As String = (New WebClient).DownloadString("http://192.168.101.1:100/list_product?username=SIP12&category=ROAMING&to=0811&payment_method=LINKAJA&json=1")
Dim jarr As JArray = Linq.JArray.Parse(json)
Dim sKatagori As String
For Each jtk As JToken In jarr
sKatagori = jtk.SelectToken("kategori")
DgvDigipos.Rows.Add()
DgvDigipos.Rows(DgvDigipos.Rows.Count - 1).Cells("DgvKategori").Value = sKatagori
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CekPaket()
End Sub
End Class
after I debug the result is an error like this.
Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.'
Can you help me to get a great result
Most likely this is a result of your call to the web service not returning the result you expect.
This is actually a good example of the benefits of separation of concerns and strongly typed objects. Your sub CekPaket should be broken down into 3 parts. 1) get the string. This should be a function and should use some sort of configuration to get the end point and have appropriate guards for failure, 2) parse the string into a strongly typed object (IEnumerable of whatever), this should validation to make sure that the input is good. You might want to make this function public for easy testing. And finally 3) bind your results to your UI. It looks like you are doing this part by hand, whenever possible you should allow the frame work to do this for you by providing a data source and a template for the display.

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"}

How do I add a string to an array in visual basic net

I have been looking for the specified code all day long, browsing through the MSDN libraries from microsoft, but I wasn't able to find or come up with a solution:
Question: How can I add a string to an existing array?
I have been trying this
Dim Items() As String
Items = ListBox1.Items.Cast(Of String).ToArray
Array.Reverse(Items)
Me.ListBox1.Items.Clear()
Me.ListBox1.DataSource = Items
**Items.add("Add This to my array")**
But this doesn't work unfortunately.
My code is loading a populated listbox into an array (reverses the entries, and then cleans the listbox before populating it with the array).
How can I add to this array now?
Try this.....
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Items As List(Of String)
Items = ListBox1.Items.Cast(Of String).ToList
Items.Reverse()
Items.Add("Add This to my array")
Me.ListBox1.Items.Clear()
Me.ListBox1.DataSource = Items
End Sub
End Class
almost identical code (slightly rearranged), using a List instead of an array

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