Cannot get decimal entries from array to appear in listbox - vb.net

In my VB class we've been asked to set up an array which is populated by user entries. These entries are decimal type, meant to be gas prices. There are twelve, one per month. The entries are supposed to show up one at a time, as they are entered and processed, in a list box.
I've got them showing up but they're not showing up properly. Instead of 4.55 (or whatever), the entries show up as "Decimal[] Array" (minus the quotation marks, of course).
How can I get the entries to show up properly? The code is below and it's very incomplete as I'm only about a third of the way into the project, so don't sweat that unless you see some horrible problem sticking out like a sore thumb.
Public Class GasPrices
Dim prices(11) As Decimal
Private Sub EnterButton_Click(sender As Object, e As EventArgs) Handles EnterButton.Click
prices(PriceList.Items.Count) = Convert.ToDecimal(PriceText.Text)
PriceText.Clear()
For i = 0 To 11
prices(i) = i
Next i
PriceList.Items.Add(prices)
End Sub
Private Sub PriceList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles PriceList.SelectedIndexChanged
PriceList.Items.Clear()
PriceList.Items.Add(prices)
End Sub
End Class

You're adding the entire array as one "entry". You'd need to add each individual entry instead using syntax like you've got where you access prices(i) in the loop.
Public Class GasPrices
Private prices(11) As Decimal
Private Sub EnterButton_Click(sender As Object, e As EventArgs) Handles EnterButton.Click
If PriceList.Items.Count < 12 Then
Dim price As Decimal
If Decimal.TryParse(PriceText.Text, System.Globalization.NumberStyles.Currency, Nothing, price) Then
prices(PriceList.Items.Count) = price
PriceList.Items.Add(price)
PriceText.Clear()
PriceText.Focus()
Else
MessageBox.Show("Invalid Price!")
End If
Else
MessageBox.Show("12 entries have already been entered!")
End If
End Sub
Private Sub PriceList_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles PriceList.SelectedIndexChanged
If PriceList.SelectedIndex <> -1 Then
Label1.Text = PriceList.SelectedItem
End If
End Sub
End Class

It's quite simple. With Add you add the array itself as single object to the listbox. The listbox's default behavior is to show object.ToString for each entry. And since the object is an array of decimals, you get the unwanted output.
If you want to add the elements of an array to a list, listbox, ... you use the AddRange method instead.

Related

Make the input of two combo boxes search for, read and display data from csv file

Look this question is probably going to be unanswered or really confusing. This is all in Visual Studio (VB Code is preferred).
I have this program, and basically when the program loads, I want the combo boxes to be populated with data from a CSV file(I have done this.)
Then once I choose a value from the section box, I want the competitor number combo box to only show the numbers that have the selected value from the section box (i.e dependent combo boxes). Then based of the two values chosen, I want a name to be displayed.
So if Section 1, competitor 1 is chosen, I want their name to be displayed. But if I change it to section 1 competitor 2, the name should change.
Build a class for your competitor object.
Public Class Person
Public Property ComboBox1Value As String
Public Property ComboBox2Value As String
Public Property Name As String
End Class
Then declare a collection to hold the list of objects somewhere. I added it to the top of Form1.vb. Now when you hit your Search_For_Name sub, just loop through the collection until the combobox values match those in one of the objects.
Public Class Form1
Dim MyCollection As New Collection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'Populate your collection here from your csv by declaring a new
'person for each row of your file, and then adding it to the
'collection.
End Sub
Private Sub ComboBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedValueChanged
Search_For_Name()
End Sub
Private Sub ComboBox2_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedValueChanged
Search_For_Name()
End Sub
Private Sub Search_For_Name()
For Each P As Person In MyCollection
If P.ComboBox1Value = ComboBox1.Text And P.ComboBox2Value = ComboBox2.Text Then
TextBox1.Text = P.Name
Exit For
End If
Next
End Sub
End Class

How can I write data into a row in Virtual Studio? (MS Access Database file"

I would like to make a small application what can make easier my work.
I have to make one ordering process some labels where I have a plan and from the plan I have to one excel list making with the labelnames what will be printed by the Manufacturer. We have a lot of type of the label (names) but they are fixing. (160 pieces differentnames).
So I make this always if I get a new plan then I make new label-list. I do it alway by hand cell by cell.. Sometime I have to filling out 400 cell for one plan... I don’t have a lot’s of time to this..
So I started making my first Windows app with Visual Studio(in Windows From – Visual Basic).
I found some cool video, so I already have the „basics”.
I connected one MS Access database to my Project where I would like to store the datas.
And now i have trouble.. I have some Comboboxes. I would like to choose some cases and then I would like to update the database where the rows will be filled with the correct values. If its done, i can this exporting to excel and sendig forward to the Manufacturer.
I have a textbox where I write the Plan name (it linked to the database first Column)
And then:
So the Combobox1 have Sektor A, B, C, D ,E, F (six value)
The Combobox2 have 09RRU, 09RSU, 18RRU ... empty - (eight value)
The Combobox3 have 21RRU, 21RSU, 26RRU ... empty - (eight value)
The Combobox4 have ja or nein (only two value)
and so on.. I have 8 Combobox.
My Idea:
If I select the Sektor A and 09RRU , the another two is empty and nein, then I click on the Update button I would like to get back in database 09.SekA1, 09.SekA2, AISG.SekA
If I select the Sektor A and 09RRU and 21RRU and ja, then after click Update, I would like get 09.SekA1, 09.SekA2, 21.SekA1, 21.SekA2, 09.21.SekA1, 09.21SekA2, AISG.09.21.SekA
….
I can every type of labels line by line writing if needed, I think I have to do this. I don’t think so can I dynamic Arrays making which can the different String e.g. ( Text (09) & Text (.SekA) & Text(1)) creating. I just now started the VB..
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox8.SelectedIndexChanged
SektorForm1()
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
Private Sub ComboBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
End Sub
Private Sub ComboBox4_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox3.SelectedIndexChanged
End Sub
Private Sub SektorForm1()
BEschriftungenDataSet.Standort.RRU18Column = "18.SekA1"
BEschriftungenDataSet.Standort.RRU21Column = "18.SekA2"
BEschriftungenDataSet.Standort.RRU26Column = "AISG.18.SekA"
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.StandortTableAdapter.Fill(Me.BEschriftungenDataSet.Standort)
ComboBox1.SelectedIndex = 5
ComboBox2.SelectedIndex = 3
ComboBox3.SelectedIndex = 3
ComboBox4.SelectedIndex = 1
ComboBox5.SelectedIndex = 1
ComboBox6.SelectedIndex = 1
ComboBox7.SelectedIndex = 1
ComboBox8.SelectedIndex = 0
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error GoTo SaveErr
StandortBindingSource.EndEdit()
StandortTableAdapter.Update(BEschriftungenDataSet.Standort)
MessageBox.Show("Saved")
End Sub
Could some one for me Helping what is wrong in my code? I tried some data inserting to tha database when I choose someting in Combobox1 but it doesn't work..
I get failures: BC30526 Property'RRU18Column' is 'ReadOnly' and BC30311 Value 'String' cannot be converted to 'DataColumn'..
And giving some help how I sould staring building up my cases to my Combobox chooses..
Thanks guys

How can I mirror checked items from one CheckedListBox to another?

I have 2 checklistbox controls and want the items in the second control to mirror the checked state of those in the first. For example:
Checklistbox1 = APPLE, MANGGO, BANANA, STRAWBERRY, GRAPE
Then i checked manggo and grape.
checklistbox2 = 0,1,0,0,1
How do I go about this?
This should accomplish what you want. Note that if you have a CheckedListBox2_SelectedIndexChanged event, you could get unexpected results, as this code will trigger it.
Private Sub CheckedListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckedListBox1.SelectedIndexChanged
Dim i As Integer
For i = 0 To CheckedListBox2.Items.Count - 1
CheckedListBox2.SetItemChecked(i, False)
Next
For Each i In CheckedListBox1.CheckedIndices
CheckedListBox2.SetItemChecked(i, True)
Next
End Sub
If you have a large list, this might be a bit more efficient, but you end up with the same result.
Private Sub CheckedListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckedListBox1.SelectedIndexChanged
Dim i As Integer
For i = 0 To CheckedListBox2.Items.Count - 1
CheckedListBox2.SetItemChecked(i, CheckedListBox1.GetItemCheckState(i))
Next
End Sub
Also you might want to have the checkonclick property of your listboxes set to true to save you having to click the item twice - and it yields more consitent results with both my code and the code from #josh , but if you need to do anything else when you're selecting an item, you might want it turned off

Case Statement not working with String Literals

Hi all I am trying to learn VB and am having trouble with some code I am using. I would like my program to output a specific number based on if a check box is checked using case statements but my code is not working.
Public Class frmBTPW
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
Dim dblhdr As Double
Dim dblfdr As Double
Dim dbltdr As Double
dblhdr = 24
dblfdr = 35
dbltdr = 50
Select Case "Power Wash Rental"
Case "Half Day Rental"
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
Case "Full Day Rental"
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
End Select
End Sub
Private Function Button1_Click() As CheckBox
Throw New NotImplementedException
End Function
End Class
Help would be greatly appreciated.My code isn't outputting anything in the text-box.
Beyond case statements, respectfully I think you should read up on the distinction between a literal value and a variable. "Power Wash Rental" is nothing more than a series of characters, AKA a string: (In this case "P" followed by "o" etc.) Likewise, "Half Day Rental" is a series of characters, "H" followed by "a" etc.)
"Power Wash Rental" is a literal string. So is ""Half Day Rental" and of course they will never match.
Whereas:
Dim A as string
A = TextBox1.text
Now, A is a variable. It is a string which contains whatever series of characters (text) is typed into the textbox.
This is a simple way to do it.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chkhd.tag = 24 ' store values in the check boxes
chkfd.tag = 35 ' using the tag property
chktd.tag = 50 ' and later add up the values
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
dim total as double = 0
total += IF(chkhd.checked, cdbl(chkhd.tag), 0)
total += IF(chkfd.checked, cdbl(chkfd.tag), 0)
total += IF(chktd.checked, cdbl(chktd.tag), 0)
msgbox(total)
End Sub
However, I think you might want radio buttons instead of checkboxes.
Checkboxes can all be checked. Radio buttons can only have one at a time.
This solution allows you to keep your price with the checkbox -- you could do this in the form designer instead of form load.
I would recommend reading up on Case Statements. Currently you will never get anywhere as your using a string to what, nothing. You also do not need a case for this... Also if the first condition is true and the last one is as well, the last one win's for setting the text, didn't know if you had this there for a reason or not?
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
As others have stated your Case statement isn't working because you are using string literals to compare "Power Wash Rental" to "Half Day Rental" which will always be false. Plutonix was also correct in saying that a ComboBox for the rental duration should be used. The only reason not to be is if you were calculating cumulative rental days/amounts; however in that situation you should be using some sort of NumericUpDown for your multiplier against a time duration.
Here is an example that should help you get started. You could make the structure into a type of keyed collection or make it a wrapper class for a dictionary object which would make be easier to use in code. The following may not be exactly plug-and-play with your project, however it should help give you some ideas on how to handle the situation.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.ComboBox1.Items.AddRange({PowerWashRentals.halfDayText, PowerWashRentals.FullDayText, PowerWashRentals.TwoDayText})
AddHandler ComboBox1.SelectedValueChanged, AddressOf Me.ComboBox1_SelectedChanged
End Sub
Private Sub ComboBox1_SelectedChanged(sender As Object, e As EventArgs)
Dim cBox As ComboBox = DirectCast(sender, ComboBox)
Select Case cBox.SelectedItem.ToString
Case PowerWashRentals.halfDayText
Label1.Text = PowerWashRentals.HalfDayPrice.ToString
Case PowerWashRentals.FullDayText
Label1.Text = PowerWashRentals.FullDayPrice.ToString
Case PowerWashRentals.TwoDayText
Label1.Text = PowerWashRentals.TwoDayPrice.ToString
End Select
End Sub
End Class
Public Structure PowerWashRentals
Public Const HalfDayPrice As Double = 24
Public Const FullDayPrice As Double = 35
Public Const TwoDayPrice As Double = 50
Public Const halfDayText As String = "Half Day Rental"
Public Const FullDayText As String = "Full Day Rental"
Public Const TwoDayText As String = "Two Day Rental"
End Structure

manipulating textbox variables in calculations

I have some code where I am trying to use variables in a tabpage. The first tabpage only has one text box for user entry (miles.text) and a button to do a calculation: traveltime = mileage/speed. The value from miles.text is stored into a variable called mileage while the speed used is stored in a variable called speed (me.speedtextbox.text).
Ordinarily, doing val(variable.text) works like a charm and it's not doing it in this case. When the user enters 100 for the mileage, it should be divided by 65 (the number in the database) and, therefore, the answer should be 1.53 hours. In my case, I'm getting "infinity" and whenever I do anything else with the variable, I get "when casting from a number, the value must be a number less than infinity." But it is! It's only 65 and I double-checked that the dataset said that too, which it does. Not sure why I am getting this error...thank you!
Public Class Form1
Private Property Traveltime As Decimal
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'fooDataSet.testdata' table. You can move, or remove it, as needed.
Me.TestdataTableAdapter.Fill(Me.foouDataSet.testdata)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mileage As Integer
Dim speed As Integer
mileage = Val(miles.Text)
speed = Val(Me.SpeedTextBox.Text)
traveltime = mileage / speed
txttraveltime.text = Traveltime.ToString
End Sub
Private Sub txtrate_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txttraveltime.TextChanged
End Sub
End Class
So I did a test program where it did only one thing and that was to simply read one data column in a one row database and store it to a local variable and multiply it by 1.60 except now I am getting "reference to a non-shared member requires an object reference" and it doesn't seem to recognize Me.Speed when I declare it. What am I doing wrong?
Public Class Form1
Dim Speed As Object
Dim Me.Speed As New Speed
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Speed = CDec(fooDataSet.testdataRow.Item("speed"))*1.60
Speedtextbox.text = Me.Speed.tostring
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'fooDataSet.testdata' table. You can move, or remove it, as needed.
Me.TestdataTableAdapter.Fill(Me.fooDataSet.testdata)
End Sub
End Class
Before you do anything else, you should do the following:
Open the project's properties (right-click on the Project, then select Properties)
Click on the Compile tab (left-hand side)
Select All Configurations from the dropdown menu
Select On from the Option Explicit menu.
Select On from the Option Strict menu.
Save the project
This will more than likely cause a lot of errors to be displayed, but fixing these errors will substantially improve your application's health.
Now, that that is done, the following code will fix the problems in the button click:
Dim mileage As Integer
Dim speed As Integer
If IsNumeric(Me.Miles.Text) Then
mileage = CInt(Me.Miles.Text)
End If
If IsNumeric(Me.SpeedTextBox.Text) Then
speed = CInt(Me.SpeedTextBox.Text)
End If
If speed <> 0 Then
Traveltime = CDec(mileage / speed)
Else
Traveltime = 0
End If
txtTravelTime.Text = Traveltime.ToString
However, the code as you have it will produce correct results, so there must be something else amiss. Try the above first and if there are still issues, you can update your question with the details.
I would implement the calculation in a separate class and then use object-binding. Here is how the travel time calculator would look like:
Imports System.ComponentModel
Public Class TraveltimeCalculator
Implements INotifyPropertyChanged
Private _miles As Double
Public Property Miles() As Double
Get
Return _miles
End Get
Set(ByVal value As Double)
If _miles <> value Then
_miles = value
OnPropertyChanged("Miles")
OnPropertyChanged("Traveltime")
End If
End Set
End Property
Private _speed As Double
Public Property Speed() As Double
Get
Return _speed
End Get
Set(ByVal value As Double)
If _speed <> value Then
_speed = value
OnPropertyChanged("Speed")
OnPropertyChanged("Traveltime")
End If
End Set
End Property
Public ReadOnly Property Traveltime() As Double
Get
Return If(_speed = 0.0, 0.0, _miles / _speed)
End Get
End Property
#Region "INotifyPropertyChanged Members"
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private Sub OnPropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
#End Region
End Class
In Visual Studio, add a data source in the Data Sources panel. Choose "Object" and then select the TraveltimeCalculator (it has to be compiled, before you can do that). Now you can drag the speed, mileage and travel time fields from the data sources panel to your form. All the wire-up will happen automatically. VS automatically inserts a BindingSource and a navigator into your form. You will not need the navigator and can safely remove it. The only thing you still have to do is to add the following code in the form load event handler or in the form constructor:
Private Sub frmTravelTime_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TraveltimeCalculatorBindingSource.DataSource = New TraveltimeCalculator()
End Sub
When you enter speeds and mileages, the travel time textbox will automatically be updated. Non-numeric entries will automatically be rejected and all the text-number conversions happen automatically.
I discovered what the problem was.
To store a field from a one-line database to a local variable for calculations, apparently it has to happen in the form1_load event, after the dataadapter fill statement, like so:
Me.TestdataTableAdapter.Fill(Me.foouDataSet.testdata)
speed = Me.fooDataSet.testdata(0).speed
and just DIM speed as Decimal after the Public Class line. The same could be done for any other field you want to work with in a similar kind of single datarow:
yourvarname = Me.yourdatasetname.yourtablename(0).the_database_field_you_want_to_fetch
(Wow! Did I just write something textbooky? LOL)
Then, after the button click, to do a calculation, it is:
traveltime = CDec(miles.Text/ speed)
txttraveltime.Text = traveltime.ToString
making sure to DIM traveltime as Decimal.
Works! The problem was the (0) to indicate row 0 (because it's only one row.) Thank you everyone for your help, especially Competent_Tech. I learned something and I'm happy that I could get back to you guys and share.