How to solve system.invalidcastexception in vb.net - vb.net

Well, i have this piece of code. I want to store the contents of a textbox into an array of strings (i prefered to do it with a list of strings) and then to print each element of the array into another textbox. However when i try to compile this code i get this error message:
System.InvalidCastException: 'Conversion from string "" to int is not valid'
FormatException: input string is not in the correct format
Any suggestions?
Public Class NewUser
Dim textUser As String
Dim strUserName As New List(Of String)
Private Sub btnCreateUser_Click(sender As Object, e As EventArgs) Handles btnCreateUser.Click
textUser = txtNewUser.Text
If textUser <> "" Then
strUserName.Add(textUser)
txtNewUser.Clear()
Else
MsgBox("Username or Password is missing. Try again!")
End If
For Each i As String In strUserName
TextBox1.Text = String.Join(",", strUserName(i))
Next i
End Sub
End Class

It's not clear to me at all what you're trying to do here:
For Each i As String In strUserName
TextBox1.Text = String.Join(",", strUserName(i))
Next i
For starters, i is a string and you're trying to use it like an integer as an index of an array. But even if you were to correct it to this:
String.Join(",", i)
That's still trying to join one string. That probably won't compile either, but even if it does it won't logically do anything. Aside from that, you're overwriting TextBox1.Text every time the loop iterates, so at best it's only ever going to equal the last value in the array.
If you're just trying to join the array into that text box, that's one line:
TextBox1.Text = String.Join(",", strUserName)
No loop required.

Related

Get a specific value from the line in brackets (Visual Studio 2019)

I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function

loop - reading text after a certain string up until a certain string

start=AKS-RHzlSXSftLGYdBNk.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1&
For every instance of the word 'start' I need to be able to get the text after the first full stop, right up until the & symbol. E.g. 'eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1'.
There will be more than one instance of this. They will need to be appended to a listbox.
What is the simplest/quickest way to do this? (Using possibly streamreader - text file)
The simplest and quickest way will be to read each line, and check if it .StartsWith("start="). If so, then get the .IndexOf(".") and the .IndexOf("&", <whereever the first indexOf was>). Get the .SubString which encompasses those two values. I'm sure you can write the code yourself from that ;)
I tested this function with a button click, output text each line on a textbox. I am sure you can adapt this to your code.
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtResults.Text = ""
Dim ParseString As String
ParseString = "start=123341.23124&kjdshfkjsdaksdstart=1231.2321312&kadhskjashdkjastart=1231.23126789898&skjdfhkjsd"
Dim Delimiters() As String = New String() {"start="}
Dim Words() As String
Words = ParseString.Split(Delimiters, CompareMethod.Text)
For Each Part In Words
Dim Middle As String
Middle = Part.Split(".").Skip(1).Take(1).FirstOrDefault()
Dim Good As String
Good = Middle.Split("&").FirstOrDefault()
txtResults.Text += Good + vbNewLine
Next
End Sub
Output was
23124
2321312
23126789898
Added 31104 lines to a string and ran, took about 11 seconds to run on my laptop. Might be too slow for your app?

I need to know how to avoid the System.Data.DataRowview in vb 2010

I have an issue with my code; and would appreciate some assistance getting her to do what I want without an annoying error. Read the databound listbox strings, find the user selected string and write said string to a file.
Private Sub btnContinue_Click(sender As System.Object, e
As System.EventArgs) Handles btnContinue.Click
' 1st file and mySQL Update to testing table
If txtLocation.Text.ToString <> "" And txtUnitTested.Text.ToString <> "" Then
Dim filewriter As New System.IO.StreamWriter(
"C:\Users\OER\Documents\Visual Studio 2010\Projects\frmTest1_0.txt")
Dim curItem = lstCustomer.SelectedItem
Dim now As DateTime = DateTime.Now
With filewriter
.WriteLine(vbCrLf + (now.ToString("F"))) ' Write the DateTime to the file
End With
For Each objDataRowView As DataRowView In lstCustomer.SelectedItems
Dim item As String
For Each item As DataRowView In Me.lstCustomer.Items.Item("customer")
item = String.Parse(lstCustomer.SelectedValue)
WriteLine(curItem(item))
Next item
Next ' THIS IS THE FOR LOOP I AM HAVING ISSUES WITH!!!!!!!
With filewriter
.WriteLine(vbCrLf + txtLocation.Text + vbCrLf + txtUnitTested.Text)
End With
filewriter.Close()
frmTest1.Show()
Else
MsgBox("Please Type the Location and Unit Tested!!!", vbCritical)
txtLocation.Clear()
txtUnitTested.Clear()
txtLocation.Focus()
End If
These loops:
For Each objDataRowView As DataRowView In lstCustomer.SelectedItems
Dim item As String
For Each item As DataRowView In Me.lstCustomer.Items.Item("customer")
item = String.Parse(lstCustomer.SelectedValue)
WriteLine(curItem(item))
Next item
Next
Are going to cause you some problems. You have declared a loop variable with the same name as another variable. And then you are assigning a value to it.
Also, I am not very clear on what the purpose of the two loops are. I am somewhat confused about what you are trying to accomplish in this section of code. I would start by renaming the variable in this line:
Dim item as String
I am going to use this for an example:
Dim result as string
Make that something else, and you cannot then change the value of item (since that is the loop variable) in the loop. That will cause an error.
Changing the code inside the loop to:
result = String.Parse(lstCustomer.SelectedValue)
Odds are this still won't get you to where you are trying to go, but it is a good start. Unless each item in your lstCustomer contains multiple items to iterate through I think you probably only need that first, outer loop, anyway.
If your loop starts like this:
For Each objDataRowView As DataRowView In lstCustomer.SelectedItems
Then I think you will want:
objDataRowView.Item("customer")
as what is output. I think that will be the value of the customer field from your table.
You are basically saying that this row has a column called customer.... I would like that value please.

VB.NET AlphaNumeric into integer

If Textbox1.text contains a string value of ZU4, how can I convert that string to it's numeric ASCII codes, and output it to a second text box?
I'd like to do this using a FOR LOOP conditional statement which will read every character in INPUT?
Sample:
INPUT Textbox1.Text = ZU4
OUTPUT Textbox2.Text = 908552
You could also use LINQ:
TextBox2.Text = String.Join(String.Empty, From c In Textbox1.Text.ToCharArray Select (Asc(c).ToString))
Could be useful on some job interviews... :)
All of the other answers will work with your given example, however, some of the suggestions are using unicode encoding rather than ASCII. If strictly adhering to ASCII encoding is important, then you should explicitly specify the encoding that you want to use.
Convert.ToInt32 uses UTF-16 encoding. I'm not sure what CInt will do, but I suspect it works the same way. Using Asc is better, but it is still dependent on the code page setting for the thread, so it's still not entirely safe. Besides that, Asc is an old VB6 function which is provided in VB.NET, primarily for backwards compatibility.
Therefore, I would recommend using the ASCIIEncoding class instead. You can get an instance of that class using the shared ASCII property of the Encoding class in the System.Text namespace, for instance:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
builder.Append(b.ToString())
Next
Return builder.ToString()
End Function
Then, you can call the function like this:
Textbox2.Text = ConvertTextToAsciiDigits(Textbox1.Text)
However, I can't imagine that the resulting string will be usable unless every character results in a two digit number. Therefore, I would force it to be two digits by doing something like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException() ' Throws an exception if the value is three digits
End If
builder.Append(b.ToString("00")) ' Adds a leading zero to one-digit values
Next
Return builder.ToString()
End Function
To add a hyphen after every fourth digit, as you mentioned in a comment below, you could just keep track of the total digits added since the last hyphen, like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
Dim digitsSinceHyphen As Integer = 0
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException()
End If
builder.Append(b.ToString("00"))
digitsSinceHyphen += 2
If digitsSinceHyphen >= 4 Then
builder.Append("-")
digitsSinceHyphen = 0
End If
Next
Return builder.ToString()
End Function
Here is one approach, in C#:
Textbox2.Text = string.Empty;
foreach(var c in Textbox1.Text)
{
Textbox2.Text += ((int)c).ToString();
}
VB.NET:
Textbox2.Text = String.Empty
For Each c As Char In Textbox1.Text
Textbox2.Text = Textbox2.Text + Convert.ToInt32(c).ToString()
Next
It:
Clears out Textbox2.Text
Loops over each character in the input
Concatenates the integer value output as a string to the output text
TextBox2.Text = ""
For i As Integer = 0 To TextBox1.TextLength - 1
TextBox2.Text += Asc(TextBox1.Text(i)).ToString()
Next
i modified the code from this Link
Function AsciiEncode(ByVal value As String) As String
Dim encValue As New System.Text.StringBuilder(value.Length * 6)
Dim c As Char
For Each c In value
encValue.Append(Convert.ToInt32(c))
Next
Return encValue.ToString()
End Function
usage:
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = AsciiEncode(TextBox1.Text)
End Sub

Visual Basic Value of type '1-dimensional array of String' cannot be converted to 'String

Im working on a program and I get this "Value of type '1-dimensional array of String' cannot be converted to 'String'."
heres the code that gets this error:
Label4.Text = System.IO.Directory.GetDirectories(Backup)
And heres the string
Dim Backup As String
Backup = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.MineRbu"
The GetDirectories() method returns an array of strings. You're setting that to a string property (.Text).
Try this instead:
Dim dirs() As String = System.IO.Directory.GetDirectories(Backup)
Label4.Text = string.Join(vbCrLf, dirs)
This will extract all the directories into an array, then put each item onto your label (separated by a new line).
The System.IO.Directory.GetDirectories(Backup) returns an array of strings.
You probably need to change it to this:
'This will insert each value returned from GetDirectories'
For Each Dir as String in System.IO.Directory.GetDirectories(Backup)
Label4.text &= Dir & VbCrLF
Next
'Alternatively, if you just need the first result:'
Label4.text = System.IO.Directory.GetDirectories(0)
References
GetDirectories
You should declare Backup as DirectoryInfo not of type string
Dim Backup As DirectoryInfo = New DirectoryInfo(path)
see Microsoft Example