String Letter Converted on 0 - vb.net

I want to make a program (on VB) to Copy a especific Folder from an USB, but whatever that I Use (TextBox, ComboBox, ListBox), always the DriveR Letter (C: for test) is converted to a 0, so te program doesn't works. If I Use another Dim...As.., like Integer, I get the "An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll" Error
here is my Code:
Private Sub RespJ_Click(sender As Object, e As EventArgs) Handles RespJ.Click
Dim CarpetaI, CarpetaL, ID As String
Dim Letra As Integer
Letra = Val(combobox1.Text)
ID = Val(IDTB.Text)
CarpetaI = Letra + ":\WPSystem\AppData\" + ID
CarpetaL = "C:\RespaldoWP\WPSystem\AppData\" + ID
Label1.Text = CarpetaI
'My.Computer.FileSystem.CreateDirectory(CarpetaL)
'My.Computer.FileSystem.CopyDirectory(CarpetaI, CarpetaL, True)
End Sub
*The last 2 lines are commented because I want to test the Code (Using a label to see if the path is correct) before to make it copy/past on real/testing files

There are two problems here:
Your variable should be a String:
Dim Letra As String
Don't use the Val function to read the drive letter from the combo box:
Letra = combobox1.Text

Related

Error System.InvalidCastException: 'Conversion from string "" to type 'Integer' is not valid.'

I'm trying to open a file that I already add to my TreeView control by clicking it twice, it should appears in a DataGridView control, when a I do it, it shows me the next error:
System.InvalidCastException: 'Conversion from string "Book1.csv" to type 'Integer' is not valid.'
At the Direccion variable, I'm not pretty sure, what it happening. Does any one could orient me? Please.
Public Sub TV_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As
TreeNodeMouseClickEventArgs) Handles TV.NodeMouseDoubleClick
Dim NombreNodo As String = TV.SelectedNode.Text
Dim parseCSV As String
Dim tstSeq() As String
Dim Direccion As String = My.Computer.FileSystem.CurrentDirectory(NombreNodo)
'Dim x As String = Path.GetFullPath(NombreNodo)
'MessageBox.Show(Direccion)
tstSeqDataGrid.Rows.Clear()
Using FileSystem As FileStream = File.Open(Direccion, FileMode.Open, FileAccess.Read)
Dim TestReader As New System.IO.StreamReader(FileSystem)
Do While TestReader.Peek <> -1
parseCSV = TestReader.ReadLine()
tstSeq = parseCSV.Split(",")
tstSeqDataGrid.Rows.Add(tstSeq)
TstSequenceLoaded = True
Loop
TestReader.Close()
FileSystem.Close()
End Using
End Sub
I am assuming that the TreeView is loaded with file names and those files are located in the directory where the code is running. You can see the value of Direccion in the Immediate Window. Using Debug.Print instead of a message box saves you from the embarrassment of forgetting to remove the message box in the production code. The Debug.Print will just be removed.
I returned an array of lines in the file with ReadAllLines. Then loop through the lines as you did.
With Option Strict On (as it should be) you need to add the lower case c following "," so the compiler knows you intend it as a Char not a String.
Public Sub TV_NodeMouseDoubleClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TV.NodeMouseDoubleClick
Dim Direccion = My.Computer.FileSystem.CurrentDirectory & TV.SelectedNode.Text
Debug.Print(Direccion)
tstSeqDataGrid.Rows.Clear()
Dim lines = File.ReadAllLines(Direccion)
For Each line In lines
Dim tstSeq = line.Split(","c)
tstSeqDataGrid.Rows.Add(tstSeq)
Next
TstSequenceLoaded = True
End Sub

Visual Basic rename a group of files

I'm starting with Visual Basic and use Visual Studio 2012 and trying to make a tool for renaming a group of files.
How it shoul be:
1- With the "Select Files" button, I can choose the files and they are listed in the ListBox
2- "Old value" is a textbox and is the value to be changed in the filename. For example: fff
3- "New value" is a textbox and is the new value that should replace the old. For example: zzz
4- Rename is a button to start the process.
To rename only one file it's not a problem.
But how to rename all the files from the ListBox which are containing the Oldvalue ?
Can you please help me!
Thanks
I suggest looping over the selected files in the listbox, checking to see which ones contain the OldValue string.
You could use string.contains http://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Sounds like you have the replace function sorted since you say it's no problem to do just one file.
Thank you 70Mike.
But I have some problem with the loop.
If it works only for 1 file and not for all.
Here is my code:
Public Class frmRename
Private Sub cmdSelectFile_Click(sender As Object, e As EventArgs) Handles cmdSelectFile.Click
If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
For Each S As String In OpenFileDialog1.FileNames
lstSelectFiles.Items.Add(S)
Next
Else : Exit Sub
End If
End Sub
Private Sub cmdRename_Click(sender As Object, e As EventArgs) Handles cmdRename.Click
Try
For LC As Integer = 0 To lstSelectFiles.Items.Count - 1
Dim s1 As String = lstSelectFiles.Items(LC)
Dim s2 As String = txtbOld.Text
Dim b As String
b = s1.Contains(s2)
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b)
Do While b = True
Dim oldFile As String = lstSelectFiles.Items(LC)
Dim newFile As String = Replace(lstSelectFiles.Items(LC), txtbOld.Text, txtbNew.Text)
If File.Exists(oldFile) And Not File.Exists(newFile) Then
File.Move(oldFile, newFile)
Kill(oldFile)
End If
Loop
Next
Catch ex As Exception
MsgBox("No file renamed")
End Try
End Sub
End Class

check for uniqueness of employee id number

Cant seem to figure out how to check for a unique Employee id Number. I know the validation has to go in the form load, just not sure how to go about it.
Public Class Form1
Dim filename As String
Dim dataFile As System.IO.File
Dim dataWrite As System.IO.StreamWriter
''LOADING AND WRITE TO TEXT DOCUMENT
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'asks user for file name
filename = InputBox("Enter output file name")
If IO.File.Exists(filename) Then
dataWrite = IO.File.AppendText(filename)
Else
MessageBox.Show("filename does not exist")
filename = InputBox("Enter output file name")
dataWrite = IO.File.CreateText(filename)
End If
cboDepart.Items.Add("Accounting")
cboDepart.Items.Add("Administration")
cboDepart.Items.Add("Marketing")
cboDepart.Items.Add("MIS")
cboDepart.Items.Add("Sales")
End Sub
'------
Public EMPLOYEEIDS As String
Dim employeeID1 As ServerData()
Dim employeeID2 As ServerData()
Dim reader As String = My.Computer.FileSystem.ReadAllText("servers.lst")
Dim s() As String
Dim Totalemployeeids As String = CStr(reader.Length)
Dim x As Integer = 0
Dim myArray As String() = reader.Split("|"c)
For x = 1 To Totalemployeeids
employeeID1(x).ServerName = myArray(0)
employeeID2(x).IDname = myarray(0)
Form1_load.ListBox1.Items.Add(Servers(x).ServerName)
x += 1
Next
Structure ServerData
End Structure
End Class
You usually do not insert a unique ID from the client side. Instead, it is inserted automatically by the database server. There is a way to retrieve an inserted ID back, if you need it for display (can also act as a confirmation that a record was successfully inserted):
SELECT SCOPE_IDENTITY()
An example is shown in this answer:
How to get last inserted id? (C#)
On the client side, you need to implement insertion of everything but the ID, in this case you don't need to check for uniqueness. There may be other validation issues upon commit though (unique key violation, data type mismatch) - make sure you catch exceptions and display them to the user as appropriate.

VB 2010 array/write array to file

I'm close to getting this to work, but currently can't get any output to display in the listbox. I had it working, but needed to move some things around to get the join function to work.
In my program, a user enters input into a textbox and an array is displayed in a listbox based on what they type in. For example, if they type in "a", all foods (in the textfile that is connected to the program) that start with "a" will be displayed.
When there is output, I need to find a way to name this array (which is created based on what the user inputs) and join all of the items in the listbox (example: foods stacked on top of each other in the listbox will be shown at the bottom as a string).
I am posting the code that I have thus far; all of the errors that I'm getting (and potentially my logic errors) are just in the first public class until the end of the first if-next statement:
Public Class frmFoods
Dim foods() As String = IO.File.ReadAllLines("foods.txt")
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
For Each food As String In foods
smallerarray = listfoods(Letter)
lstOutput.Items.Add(Letter)
userarray = Join(smallerarray, ", ")
lstOutput.Items.Add(userarray)
Next
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
Function listfoods(ByVal letter As String) As String()
Dim foodarray(foods.Count - 1) As String
Dim counter As Integer = 0
For Each food As String In foods
If food.StartsWith(letter) Then
foodarray(counter) = food
counter += 1
End If
Next
ReDim Preserve foodarray(counter - 1)
Return foodarray
End Function
you need to save the results of the listfoods function in a dictionary or similar and associate it with a key if you want to 'Name' it, although its not clear why you need to do this
As for listing the foods starting with the particular letter, you just need to iterate your result of the function listfoods and separate each one by a comma don't you?
What you have now will create many lists of each food as you are getting the list of food beginning with a particular letter for each food.. As I understand the question you only need to do that once.
Example:
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
'get all items from the file which begin with the letter the user chose
smallerarray = listfoods(Letter)
'add that letter to the output listbox
lstOutput.Items.Add(Letter)
'join all of the elements which begin with that letter
'into a single comma separated string
userarray = Join(smallerarray, ", ")
'add that string to the output
lstOutput.Items.Add(userarray)
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
it would probably be useful for you to step through the code and see the values of the variable at each place and compare this with what you expect to see if you can see where the actual value differs from what your logically expect so you can start to identify where the issue is

Error In VB.Net code

I am getting the error "Format Exception was unhandled at "Do While objectReader.Peek <> -1
" and after. any help would be wonderful.
'Date: Class 03/20/2010
'Program Purpose: When code is executed data will be pulled from a text file
'that contains the named storms to find the average number of storms during the time
'period chosen by the user and to find the most active year. between the range of
'years 1990 and 2008
Option Strict On
Public Class frmHurricane
Private _intNumberOfHuricanes As Integer = 5
Public Shared _intSizeOfArray As Integer = 7
Public Shared _strHuricaneList(_intSizeOfArray) As String
Private _strID(_intSizeOfArray) As String
Private _decYears(_intSizeOfArray) As Decimal
Private _decFinal(_intSizeOfArray) As Decimal
Private _intNumber(_intSizeOfArray) As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'The frmHurricane load event reads the Hurricane text file and
'fill the combotBox object with the data.
'Initialize an instance of the StreamReader Object and declare variable page 675 on the book
Dim objectReader As IO.StreamReader
Dim strLocationAndNameOfFile As String = "C:\huricanes.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Please restart application when available"
'This is where we code the file if it exist.
If IO.File.Exists(strLocationAndNameOfFile) Then
objectReader = IO.File.OpenText(strLocationAndNameOfFile)
'Read the file line by line until the file is complete
Do While objectReader.Peek <> -1
**_strHuricaneList(intCount) = objectReader.ReadLine()
_strID(intCount) = objectReader.ReadLine()
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
intCount += 1**
Loop
objectReader.Close()
'With any luck the data will go to the Data Box
For intFill = 0 To (_strID.Length - 1)
Me.cboByYear.Items.Add(_strID(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Me.Close()
End If
End Sub
Put a break-point on these lines and step through your code:
_decYears(intCount) = Convert.ToDecimal(objectReader.ReadLine())
_intNumber(intCount) = Convert.ToInt32(objectReader.ReadLine())
Whatever is being returned by ReadLine isn't in the proper decimal or integer format when passed to the converters. You'll need to add some try/catch blocks around the do-while loop operations to handle it gracefully and make sure your data is formatted the way you expected since the wrong parts are being used in this scenario.
Also, each call to ReadLine is returning an entirely new line and the Peek check won't account for those. As long as you can trust your data that's fine.
Instead of using Convert.ToDecimal an Convert.ToInt32, try using Decimal.TryParse() and Int32.TryParse(). If they don't parse, you know your file isn't setup correctly. If they do parse, then you've loaded the value into a variable for your use.
EDIT:
Use it like this.
Dim myDecimal As Decimal
If Decimal.TryParse(objectReader.ReadLine(), myDecimal) Then
'your string successfully parsed. Use myDecimal however you want. It has the parsed value.
Else
'your string is not a decimal. Now that you know that, you can handle this situation here without having to catch an exception.
End If