How to set a Textbox value as double and make is empty without using " " in VB.net windows form application? - vb.net

Here is the code
Public Partial Class MainForm
Public Sub New()
' The Me.InitializeComponent call is required for Windows Forms designer support.
Me.InitializeComponent()
'
' TODO : Add constructor code after InitializeComponents
'
End Sub
Sub Label4Click(sender As Object, e As EventArgs)
End Sub
Sub Button2Click(sender As Object, e As EventArgs)
Dim poundInAKg As Double = 2.20462
Dim KGInAPound As Double = 0.453592
If pound.Text = " " Then
MessageBox.Show("Please fill atleast one value Kilo or Pound : ")
End If
kilo.Text = Val(pound.Text) * 0.453592
'pound.Text = Val(kilo.Text / 2.20462 )
End Sub
Sub MainFormLoad(sender As Object, e As EventArgs)
End Sub
End Class
The error is Implicit conversion from 'Double' to 'String'. (BC42016)
Please help

You should use the double.TryParse method to try to convert the user input (a string) to a double value, then, if the conversion is successful, execute the moltiplication and reconvert everything back to a string
Dim poundInAKg As Double = 2.20462
Dim KGInAPound As Double = 0.453592
Dim poundVal As Double
if double.TryParse(pound.Text, poundVal) Then
kilo.Text = (poundVal * 0.453592).ToString()
else
MessageBox.Show("Please fill atleast one value Kilo or Pound : ")
End If

Related

How to use IO.File.WriteAllLines(FileName, OutputArray) in VB

When using this code in VB I get the error:
System.InvalidCastException: 'Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Collections.Generic.IEnumerable`1[System.String]'.'
Can someone please give me the correct usage?
Full code:
Public Class Form1
Dim OutputArray As New ArrayList
Dim i = 0
Dim Registrationdata
Dim FileName As String = Application.StartupPath & "\Output.txt"
Private Sub IssueTicket_Click(sender As Object, e As EventArgs) Handles IssueTicket.Click
Dim Speed As Integer
If Integer.TryParse(Speedbox.Text(), Speed) Then
If Speed <= 20 Or Speed > 300 Then
MessageBox.Show("Please enter a valid speed between 20-200")
ElseIf Registrationbox.Text() = Nothing Or Not Registrationbox.Text() Like "???? ???" Then
MessageBox.Show("Please enter a vaild registration to continue e.g '1234 123'.")
ElseIf Not IDBox.Text().StartsWith("9") Or Not IDBox.TextLength = 6 Or Not IsNumeric(IDBox.Text()) Then
MessageBox.Show("Please enter a valid OfficerID starting with '9' and is 6 numbers long.")
Else
OutputArray.Add(Speed)
OutputArray.Add(Registrationbox.Text())
OutputArray.Add(IDBox.Text())
MessageBox.Show("Ticket saved")
i += 1
End If
End If
End Sub
Private Sub SaveToFile_Click(sender As Object, e As EventArgs) Handles SaveToFile.Click
Registrationbox.Text() = Registrationdata
IO.File.WriteAllLines(FileName, OutputArray)
End Sub
End Class
To solve your problem quickly you could change your code to:
Dim OutputArray As New List(Of String)
...
OutputArray.Add(Speed.ToString())
OutputArray.Add(Registrationbox.Text())
OutputArray.Add(IDBox.Text())
Problem with your code is that ArrayList doesn't implement an IEnumerable interface, while List does and so File.WriteAllText works; but List(Of String) wants all the items to be of type string, so you have to convert your int to string before pushing it into the list.

Multiple Search Criteria (VB.NET)

So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next

Search from a list of string() in VB.NET

I am trying to find if mylines() contains a value or not. I can get the value by mylines.Contains method:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
If mylines.Contains("food") Then
MsgBox("Value Exist")
End If
But the problem is that I want to check if mylines() contains a line which starts with my value. I can get this value from a single line by mylines(0).StartsWith method. But how do I find a string from all the lines which is starting from some value, e.g. "mysearch" and then get that line number?
I am using a for loop to do so, but it is slow.
For Each line In mylines
If line.StartsWith("food") Then MsgBox(line)
Next
Constrained to code for .NET 2.0, please.
Here's one way with Framework 2.0 code, simply set SearchString with the the string you want to search for:
Imports System.IO
Public Class Form1
Dim SearchString As String = ""
Dim Test() As String = File.ReadAllLines("Test.txt")
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SearchString = "Food"
End Sub
Private Function StartsWith(s As String) As Boolean
Return s.StartsWith(SearchString)
End Function
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim SubTest() As String = Array.FindAll(Test, AddressOf StartsWith)
ListBox1.Items.AddRange(SubTest)
End Sub
End Class
When I test this with a file with 87,000 lines, it takes about .5 sec, to fill the listbox.
I'm not a VB guy, but I think you could use Linq:
Dim mylines() As String = IO.File.ReadAllLines(mypath)
??? = mylines.Where(Function(s) s.StartWith("food")) //not sure of the return type
Check out: How do I append a 'where' clause using VB.NET and LINQ?

Using the Content of Textbox as a variable in VB (2012)

In the code below b textbox will contain the string "a.text" what I want b textbox to be the evaluation of the content of the string "a.text" which is the word Test. Please don't suggest:
b.text = a.text
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim t As String
a.Text = "Test"
t = "a.text"
b.Text = t
End Sub
End Class
Check out Controls collection of your form. You can find an item based on its name.
Also check out this answer
VB .NET Access a class property by string value
So, you could take your string, split it by the ".", find the control using the Controls Collection, and then get the property using the second half of your string using Reflection.
Of course, if you are just looking for the Text of the textbox, you just need to use the collection and forget the reflection. Like this..
For i As Integer = 1 To 25
.fields("Field" & i).value = Me.Controls("QAR" & i).Text
Next
You can do what you asked for using Reflection ... I'm not an enormous fan of it for something like this, but here's how it would look in your code:
Imports System.Reflection
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
a.Text = "Hello"
Dim t As String = "a.Text"
b.Text = DirectCast(SetValue(t), String)
End Sub
Public Function SetValue(ByVal name As String) As Object
Dim ctrl As Control = Me.Controls(name.Split("."c)(0))
Return ctrl.GetType().GetProperty(name.Split("."c)(1)).GetValue(ctrl, Nothing)
End Function
End Class
This would set textbox a's value to "Hello" and then copy that to textbox b using the reflection method.
Hope this helps!

Moving single member of an Object in List into an array for usew in a calculation

I have a List of objects(Appliance as String and KwHHr as Double), applianceListReturn , in Visual Basic 2010. Each object has two members. I would like to take one member(KwHHr) of the same type from each object and make an array out of those single members. I am new to VB and this is not as easy as it first appeared. I have attempted to use a `for each loop to achieve this but it only returns one value. This is my code:
Imports System.Collections.Generic
Public Class Form1
Private ApplName As String '= Nothing
Private ApplKwCost As Double
Dim ConvAppliance As String
Dim ConvKwHHr As String
Public KwhCost As Double = 0
Dim ApplianceCost As New ArrayList()
'create structure for object in list
Private Structure Appliance
'public Variables
Public Appliance As String
Public KwHHr As Double
' provide get methods to allow return of objects in a formatted way
Public ReadOnly Property ApplianceInfo() As String
Get
Return Appliance & " " & KwHHr
End Get
End Property
Public ReadOnly Property ApplianceInfo2() As String
Get
Return Appliance & " " & KwHHr
Return KwHHr
End Get
End Property
Public Overrides Function ToString() As String
Return ApplianceInfo2
End Function
End Structure
Private ApplianceObj As Appliance
Dim arraylistReturn As New List(Of Appliance)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' choose KwHr price
KwCost.Text = KwhCost
' add appliance data to list
ApplianceObj.Appliance = "Washer"
ApplianceObj.KwHHr = 1.25
arraylistReturn.Add(New Appliance With {.Appliance = ApplianceObj.Appliance, .KwHHr = ApplianceObj.KwHHr})
ApplianceObj.Appliance = "Dryer"
ApplianceObj.KwHHr = 1.3
arraylistReturn.Add(New Appliance With {.Appliance = ApplianceObj.Appliance, .KwHHr = ApplianceObj.KwHHr})
ApplianceObj.Appliance = "Toaster"
ApplianceObj.KwHHr = 1.54
arraylistReturn.Add(New Appliance With {.Appliance = ApplianceObj.Appliance, .KwHHr = ApplianceObj.KwHHr})
End Sub
Private Sub ApplAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ApplAdd.Click
KwhCost = KwCost.Text
Dim newArray() As Double = {1.25, 1.3, 1.54}
'enter appliance data
ApplianceObj.Appliance = TxtBxApplAd.Text
ApplianceObj.KwHHr = TextBoxKwhUse.Text
ApplianceCost.Add(ApplianceObj.KwHHr)
'displays added appliances in applist listbox
displayAppliance(ApplianceObj)
'add applianceobj entries to arraylistreturn
arraylistReturn.Add(New Appliance With {.Appliance = ApplianceObj.Appliance, .KwHHr = ApplianceObj.KwHHr})
For Each App As Appliance In arraylistReturn
ArrayDispBox.Items.Add(App.ApplianceInfo.ToString())
Next
ReDim Preserve newArray(arraylistReturn.Count())
'count items in list
'AppList.Items.Add(arraylistReturn.Count().ToString)
newArray(arraylistReturn.Count()) = TextBoxKwhUse.Text
Dim sum As Double = 0
For int As Integer = 0 To newArray.GetUpperBound(0)
sum += newArray(int)
TextBoxTotal.Text = sum.ToString()
Next int
End Sub
Private Sub displayAppliance(ByVal App As Appliance)
AppList.Items.Add(App.ApplianceInfo2)
End Sub
' get selected appliances for calculation
Private Sub ArrayDispBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ArrayDispBox.SelectedIndexChanged
AppList.Items.Add(arraylistReturn.Item(ArrayDispBox.SelectedIndex))
End Sub
End Class
I hope this makes sense. Thank you for your help.
You can use LINQ to Object to achieve that:
Dim results As Array(Of String) = applianceListReturn.Select(Function(a) a.KwHHr).ToArray()