I get an error when calling a textbox from form1 - vb.net

I'm having issues with this:
I have this code on Form2:
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lbl0, lbl1, lbl11, lbl2, lbl22, lbl3, lbl33, lbl4, lbl44, lbl5, lbl55, lbl6, lbl66, lbl7, lbl77 As New Label
lbl0.Text = "ACCESORIOS"
lbl0.Font = New System.Drawing.Font("MS Reference Sans Serif", 15.75, FontStyle.Bold)
lbl0.Location = New Point(110, 12)
lbl0.AutoSize = True
Me.Controls.Add(lbl0)
lbl1.Text = "Té 180°"
lbl11.Text = Te180
lbl2.Text = "Té 90° Empalme - Codo Triple"
If form1.TextBox3.Text <> 0 Then
lbl22.Text = 0
Else
lbl22.Text = (Int(form1.TextBox1.Text) + Int(form1.TextBox2.Text)) - 1
End If
lbl3.Text = "Soporte 90° T/T"
lbl33.Text = SoporteTT90
TableLayoutPanel1.Controls.Add(lbl33, 0, 0)
End Sub
End Class
Don't mind the variables not used, or the single tablelayoutpannel adding, since it's a work in progress. Anyway, this code works well the first time I run it, but when I press reset,
which is a button in form1 that contains this piece of code:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim frm = New form1
frm.Show()
Me.Close()
Te180 = 0
ContadorGlobal = 0
SoporteTT90 = 0
End Sub
I end up with this error:
An unhandled exception of type 'System.InvalidCastException' occurred
in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Double' is not valid.
I get that when the program goes through here:
If form1.TextBox3.Text <> 0 Then
lbl22.Text = 0
Else
lbl22.Text = (Int(form1.TextBox1.Text) + Int(form1.TextBox2.Text)) - 1
End If
Any help is appreciated. Many I'm not calling form1.textbox1.text correctly. Maybe I'm not resetting it properly. I have no idea since I'm not an expert. Thanks in advance!

Text property of Textboxes and Labels are of type String.
Assuming that form1.TextBox1.Text and form1.TextBox2.Text contains integer values, you're setting an arithmethic operation result to lbl22.Text which should contain a string, not a number.
Change
lbl22.Text = (Int(form1.TextBox1.Text) + Int(form1.TextBox2.Text)) - 1
By
lbl22.Text = ((Int(form1.TextBox1.Text) + Int(form1.TextBox2.Text)) - 1).ToString
Said that, the error Conversion from string "" to type 'Double' is not valid is telling you that an empty string cannot be converted to a number, so be sure both TextBox1.Text and TextBox2.Text are not empty prior to perform the arithmetic operation.

Related

I can't find the reason for InvalidCastException

I am trying to make an app like an online shop for my project. The code is fine at first(at least for me since there's no errors indications)
But when I run it and press the "Add to Cart" button, it says InvalidCastException and says that I'm trying to convert a string to double even though I am not converting anything
This is what I have so far
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim prditem As ListViewItem
Dim price, cartprice As Integer
Dim product As String
If clbParts.SelectedItem = 0 Then
product = "Power Supply"
price = 1
End If
If clbParts.SelectedItem = 1 Then
product = "CPU"
price = 2
End If
....
If rdo512gb.Checked = True Then
product = "Hard Drive (512GB)"
price = 11
End If
If rdo1tb.Checked = True Then
product = "Hard Drice (1TB)"
price = 12
End If
cartprice = Price * numQuantity.Text
prditem = lvCart.Items.Add(product)
With prditem
.SubItems.Add(numQuantity.Text)
.SubItems.Add(cartprice)
End With
If numQuantity.Text = "0" Then
MessageBox.Show("Please put the number of items you want to add", "Cart Error")
End If
MessageBox.Show("Item/s is/are added to your cart", "Cart")
numQuantity.Text = "0"
End Sub
Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
Dim total As Integer = 0
For i As Integer = 0 To lvCart.Items.Count - 1
Dim quantity = CInt(lvCart.Items(i).SubItems(1).Text)
Dim price = CInt(lvCart.Items(i).SubItems(2).Text)
total += quantity + price
Next
txtTotal.Text = total.ToString("N2")
End Sub
Private Sub cboPayment_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPayment.SelectedIndexChanged
If cboPayment.SelectedItem = 0 Then
Label10.Enabled = True
cboOnline.Enabled = True
Else
Label10.Enabled = False
cboOnline.Enabled = False
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show("Your items are being delivered in " + txtHomeAddress.Text + ", " + txtAddress.Text + "\n Please wait for the text confirmation", "Cart Error")
End Sub
End Class
Do yourself a favor and watch a YouTube video on how to debug in Visual Studio!
What you need to do is put a Breakpoint on this line:
cartprice = Price * numQuantity.Text
convert a string to double
You're multplying a number by a String! You want to do something like this:
cartprice = Price * Convert.ToDouble(numQuantity.Text)
I'd personally do a double.TryParse to see if its valid and use the output value when performing the operation.
PS: As a challenge to yourself, try and move all the code logic to a Business Logic class, then use Bingings/BindingControls so the Presentation layer is separated from the logic. That way you can Unit Test the business logic layer!

VB 2013 load datagridview from a form

I have searched the net looking for how to populate a DataGridView with the New Data "Record" that is entered into a form then save the record using the BindingNavigator.
I have a single form with the DataDridView on it and I pulled the table columns from the DataSource into the form so as to allow the people to enter new records. I then want to populate the DataGrid with the information then save it.
Private Sub BindingNavigatorAddNewItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorAddNewItem.Click
Dim RR As Integer = ACCOUNT_MOVEDDataGridView.RowCount - 2
For RC As Integer = 0 To RR
If ACCOUNT_MOVEDDataGridView(2, RC).Value Is DBNull.Value Then
'' ACCOUNT_MOVEDDataGridView(2, RR).Value = ACCOUNT_MOVEDDataGridView(15, RR).Value = 0
End If
Next
End Sub
I have figured it out, I was placing the code under BindingNavigatorAddNewItem_Click
when it should have been under the Save Item click.
Private Sub ACCOUNT_MOVEDBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles ACCOUNT_MOVEDBindingNavigatorSaveItem.Click
Call ACCDEF()
Private Sub ACCDEF()
Dim RR As Integer = ACCOUNT_MOVEDDataGridView.RowCount - 2
For RC As Integer = 0 To RR
If ACCOUNT_MOVEDDataGridView(2, RC).Value Is DBNull.Value Then
ACCOUNT_MOVEDDataGridView(2, RR).Value = Date.Now
ACCOUNT_MOVEDDataGridView(15, RR).Value = 0
Else
ACCOUNT_MOVEDDataGridView(1, RR).Value = Date.Now
End If
Next
End Sub
Which loads the DataGridView with the default values, Thanks to all that have looked at my problem.

Visual Basic Sequential Access Files

I've been working on this assignment for quite awhile, but I'm practically ripping my hair out. Before anyone jumps the gun and says I'm looking for a free handout on the assignment, please note, I've done 90% of the assignment! The program has 4 commercials in a list, you choose which one to vote for and it saves your vote and tallies it. As it tallies it in the program, it also saves it into a file. The next time you open the file, you can hit "Display vote" and it reads the file and re-tally's everything for the user.
Here's what the program looks like, at least what I have done. My issue is that when I hit display votes, nothing happens. It doesn't read in anything from the file. I tested using a message box for it to see if it displays anything from the file, and it does infact display the first item from the project. Anyone have any ideas?!
Public Class frmMain
Dim intVotes(3) As Integer
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstCom.Items.Add("Budweiser")
lstCom.Items.Add("FedEx")
lstCom.Items.Add("E*Trade")
lstCom.Items.Add("Pepsi")
lstCom.SelectedIndex = 0
End Sub
Private Sub btnSaveVote_Click(sender As Object, e As EventArgs) Handles btnSaveVote.Click
Dim outFile As IO.StreamWriter
Dim intSub As Integer
intSub = lstCom.SelectedIndex
If intSub <= intVotes.GetUpperBound(0) Then
intVotes(intSub) += 1
If IO.File.Exists("CallerVotes.txt") Then
outFile = IO.File.CreateText("CallerVotes.txt")
If lstCom.SelectedIndex = 0 Then
outFile.WriteLine("Budweiser")
ElseIf lstCom.SelectedIndex = 1 Then
outFile.WriteLine("FedEx")
ElseIf lstCom.SelectedIndex = 2 Then
outFile.WriteLine("E*TRADE")
ElseIf lstCom.SelectedIndex = 3 Then
outFile.WriteLine("Pepsi")
End If
outFile.Close()
End If
End If
lblBud.Text = intVotes(0).ToString
lblFed.Text = intVotes(1).ToString
lblET.Text = intVotes(2).ToString
lblPep.Text = intVotes(3).ToString
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCom.SelectedIndexChanged
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnDisplayVote_Click(sender As Object, e As EventArgs) Handles btnDisplayVote.Click
Dim inFile As IO.StreamReader
Dim strText As String
If IO.File.Exists("CallerVotes.txt") Then
inFile = IO.File.OpenText("CallerVotes.txt")
Do Until inFile.Peek = -1
strText = inFile.ReadLine
If strText = "Budweiser" Then
intVotes(0) += 1
ElseIf strText = "FedEx" Then
intVotes(1) += 1
ElseIf strText = "E*TRADE" Then
intVotes(2) += 1
ElseIf strText = "Pepsi" Then
intVotes(3) += 1
End If
Loop
inFile.Close()
End If
End Sub
End Class
If you look at your file I think you will see that you have only one entry. You are overwriting the file each time you click the save button by using the CreateText method.
from MSDN(emphasis mine)
This method is equivalent to the StreamWriter(String, Boolean) constructor overload with the append parameter set to false. If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten.
try using the AppendText method instead.
i.e.
If IO.File.Exists("CallerVotes.txt") Then
outFile = IO.File.AppendText("CallerVotes.txt")
You will also need to assign the values that you read in to the appropriate labels per DeanOC's answer.
I think that your problem is that you are not assigning the values from the intVotes array to the labels. At the end of btnDisplayVote_Click try adding
lblBud.Text = intVotes(0).ToString
lblFed.Text = intVotes(1).ToString
lblET.Text = intVotes(2).ToString
lblPep.Text = intVotes(3).ToString

Object returns null when it is not

I basically i have two forms, one named 'frmSettings' and another names 'frmXLExternalFile', 'frmXLExternalFile' is created from 'frmSettings', there is data passed between these two forms and when i return it using a property it returns as null. Ive tried returning it by settings it to public but that still doesnt seem to work some strange reason. I've set breakpoints and traced the variable ( actually a structure ) and it is certainly not 'null'
frmXLExternalFile
Dim XL_File As frmMain.XLSheetData
Public ReadOnly Property XLFile As frmMain.XLSheetData
Get
Return XL_File
End Get
End Property
Private Sub frmXLExternalFile_formClosing(sender As Object, e As EventArgs) Handles MyBase.FormClosing
If txtFilepath.Text <> "" And cmboName.Text <> "" Then
XL_File = New frmMain.XLSheetData
XL_File.name = cmboName.Text
XL_File.filePath = txtFilepath.Text
frmMain.settings.setXLFile()
frmMain.settings.cmboXLSheets.Text = txtFilepath.Text
End If
frmMain.settings.Enabled = True
End Sub
frmMain (This is where the structure is declared)
Public Structure XLSheetData
Dim name As String
Dim filePath As String
End Structure
frmSettings
Dim XL_FileList As List(Of frmMain.XLSheetData)
Sub setXLFile()
Dim file As frmMain.XLSheetData = frmXLExternalFile.XLFile
XL_FileList.Add(file)
cmboXLSheets.Items.Add(file.filePath)
End Sub
basically, The top form calls this the bottom method once the field - XL_File - is filled, this then uses the property - 'XLFile' - to 'Get' the object and put it in the 'frmSettings' class. As I have said, i have tried setting 'XL_File' to public and tried accessing it directly but the same exception is thrown. It is null, the combo box and text box that are used to fill the object are not null. Any help would be appreciated. Thanks.
Here's one way to do it with Show(), by passing in the "Owner" form:
In frmSettings:
Dim frmX As New frmXLExternalFile
' ... pass some data to frmX ...
frmX.Show(Me) ' <-- pass this form in as the "Owner"
In frmXLExternalFile:
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtFilepath.Text <> "" And cmboName.Text <> "" Then
XL_File = New frmMain.XLSheetData
XL_File.name = cmboName.Text
XL_File.filePath = txtFilepath.Text
Dim main As frmSettings = DirectCast(Me.Owner, frmSettings) ' <-- use the instance passed in as the owner via Show()
' ... use "main" somehow ...
main.settings.setXLFile()
main.settings.cmboXLSheets.Text = txtFilepath.Text
main.settings.Enabled = True
Else
' ... possibly do something else ...
End If
End Sub
This example demonstrates a ShowDialog() approach:
In frmSettings:
Dim frmX As New frmXLExternalFile
' ... pass some data to frmX ...
If frmX.ShowDialog() = Windows.Forms.DialogResult.OK Then ' <-- execution in this Form STOPS until "frmX" is dismissed
' Retrieve the value from out "frmX" instance:
Dim file As frmMain.XLSheetData = frmX.XLFile
' ... do something with "file" ...
XL_FileList.Add(file)
cmboXLSheets.Items.Add(file.filePath)
cmboXLSheets.Text = file.filePath
End If
In frmXLExternalFile:
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtFilepath.Text <> "" And cmboName.Text <> "" Then
XL_File = New frmMain.XLSheetData
XL_File.name = cmboName.Text
XL_File.filePath = txtFilepath.Text
' Set DialogResult, returning execution to the ShowDialog() line:
Me.DialogResult = Windows.Forms.DialogResult.OK
Else
' ... possibly do something else ...
End If
End Sub

VB.net basic error with String <-> Char Conversion

I was programming a little game to pratice myself and i went on an error I weren't able to fix :S. This is the start of an hanging game. (Dont know if its the correct name in english :) ) I need to take a word from a file, 1 per line, and let the player guess the word with a limited numbers of try.
I think my error is related to string/char comparaison and manipulation or, what i write in the text label. I tryed to find some tutorial or problem already solved on internet but nothing was really the same as this ... :(
I change the type of variable many time, read the debugger line per line but I never finded what was wrong .. :S If you are good with VB, plz help me fix that :O (you can also give your comment/improve)
Thx, TheFlame
Code:
Imports System.IO
Public Class Pendu
Public Structure StructMot
Public MotSecret() As Char
Public LettreDecouverte() As Char
End Structure
Dim Mot As StructMot
Dim i As Integer = 0
Private Sub ButtonA_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonA.Click, ButtonB.Click,
ButtonC.Click, ButtonD.Click, ButtonE.Click, ButtonF.Click, ButtonG.Click, ButtonH.Click, ButtonI.Click, ButtonJ.Click,
ButtonK.Click, ButtonL.Click, ButtonM.Click, ButtonN.Click, ButtonO.Click, ButtonP.Click, ButtonQ.Click, ButtonR.Click,
ButtonS.Click, ButtonT.Click, ButtonU.Click, ButtonV.Click, ButtonW.Click, ButtonX.Click, ButtonY.Click, ButtonZ.Click
i = i + 1
ActiveControl.Visible = False
PictureBox1.Image = ImageList1.Images(i - 1)
Dim j As Integer = 0
For j = 0 To Mot.MotSecret.Length - 1
If ActiveControl.Text = Mot.MotSecret(j) Then
Mot.LettreDecouverte(j) = Mot.MotSecret(j)
End If
Next j
Label1.Text = ""
For j = 0 To Mot.MotSecret.Length - 1
Label1.Text = Label1.Text + " "
If Mot.LettreDecouverte(j).Equals("") Then
Label1.Text = Label1.Text + "_"
Else
Label1.Text = Label1.Text + Mot.LettreDecouverte(j)
End If
Next j
End Sub
Private Sub JouerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles JouerToolStripMenuItem.Click
GenereMot()
End Sub
Private Sub Pendu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GenereMot()
End Sub
Function GenereMot()
Dim NbItems As Integer
Dim Aleatoire As New Random()
Dim NbAleatoire As Integer
ListBox1.Items.AddRange(System.IO.File.ReadAllLines("listemot.txt"))
NbItems = ListBox1.Items.Count
NbAleatoire = Aleatoire.Next(NbItems)
Mot.MotSecret = ListBox1.Items(NbAleatoire)
Return Mot
End Function
End Class
the Mot.LettreDecouverte can be Nothing i.e. not initialized as you don't set any value for it.
This can cause error to happen both in Mot.LettreDecouverte(j) = Mot.MotSecret(j) line and also in If Mot.LettreDecouverte(j).Equals("") Then... line of your code.
change your ButtonA_Click event handler code as following:
i = i + 1
ActiveControl.Visible = False
PictureBox1.Image = ImageList1.Images(i - 1)
Dim j As Integer = 0
If Mot.LettreDecouverte Is Nothing OrElse Mot.LettreDecouverte.Length < Mot.MotSecret.Length Then
Mot.LettreDecouverte = Space(Mot.MotSecret.Length) '* initiate it by enough number of space chars
End If
For j = 0 To Mot.MotSecret.Length - 1
If ActiveControl.Text = Mot.MotSecret(j) Then
Mot.LettreDecouverte(j) = Mot.MotSecret(j)
End If
Next j
Label1.Text = ""
For j = 0 To Mot.MotSecret.Length - 1
Label1.Text = Label1.Text + " "
If Mot.LettreDecouverte(j).Equals(" "c) Then '*Note: i use space char, not empty string
Label1.Text = Label1.Text + "_"
Else
Label1.Text = Label1.Text + Mot.LettreDecouverte(j)
End If
Next j
Note that the value of Mot.LettreDecouverte(j) is always a char and a char can not be an empty string as you typed in Mot.LettreDeciouverte(j).Equals(""). i initiate the LettreDeciouverte with an array of space chars such that we can check its elements comparing against " "c char.