How to find the Sum or Total of a Listbox - vb.net

I have a listbox that has two columns of date entered into it using the code:
'Press to place value into Array
Private Sub TxtMark_Enter(ByVal sender As System.Object, _
ByVal e As KeyEventArgs) Handles TxtMark.KeyDown
Dim Mark As Double
Dim DataString As String
If e.KeyCode = Keys.Enter Then
If Double.TryParse(TxtMark.Text, Mark) = False Then
MessageBox.Show(" You must enter a numeric value like 1 or 2")
TxtMark.Clear()
TxtMark.Focus()
Exit Sub
End If
If Mark < 0 Then
MessageBox.Show("Valid range is between 0 and 100, 7 would work " _
& Mark.ToString & " Does not")
TxtMark.Clear()
TxtMark.Focus()
Exit Sub
End If
If NumberOfScores < MaxEntries Then
ScoreArray(NumberOfScores) = Mark
DataString = (NumberOfScores + 1).ToString + ". " + _
NameArray(NumberOfScores).PadRight(15) + _
Mark.ToString.PadLeft(5)
Lstdisplay.Items.Add(DataString)
NumberOfScores += 1
End If
TxtMark.Clear()
TxtName.Clear()
TxtName.Focus()
Exit Sub
End If
What I want to do is have a label that does the some of the Mark automatically as the data is entered. Any ideas would be great

The solution is to iterate through all entries and add up the values:
Dim total As Double
For Each s As String In ListBox1.Items
total+= s.substring(...)
Next
Debug.WriteLine("The total is:" + total.ToString)
The tricky part is extracting the numeric value from the string.
But it would be much easier if you placed the data into a ListView control. With the values all in one column. Then you don't need to do the substring to extract the numeric values out

One idea would be to add a custom extension that returns the numeric part of the string and then use Matt Wilko's iteration as above.
To create a custom extension add a class to your project as follows:
Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices
Namespace Extensions
Public Module ExtensionMethods
<Extension()> _
Public Function GetNumeric(ByVal source As String) As String
'Takes the passed in string and returns the numeric part
Dim ReturnString As String = ""
For A = 1 To source.Length
If IsNumeric(source.Substring(A, 1)) Then
ReturnString += source.Substring(A, 1)
End If
Next
Return ReturnString
End Function
End Module
End Namespace
If you then import MyProject.Extensions on you project you can use string.GetNumeric to return the numeric part of your code.
Hope this helps you (and others).

Related

Find all instances of a word in a string and display them in textbox (vb.net)

I have a string filled with the contents of a textbox (pretty large).
I want to search through it and display all occurances of this word. In addition I need the searchresult to display some charachters in the string before and after the actual searchterm to get the context for the word.
The code below is part of a code that takes keywords from a listbox one by one using For Each. The code displays the first occurance of a word together with the characters in front and after the word - and stop there. It will also display "no Match for: searched word" if not found.
As stated in the subject of this question - I need it to search the whole string and display all matches for a particular word together with the surrounding characters.
Where = InStr(txtScrape.Text, Search)
If Where <> 0 Then
txtScrape.Focus()
txtScrape.SelectionStart = Where - 10
txtScrape.SelectionLength = Where + 50
Result = txtScrape.SelectedText
AllResults = AllResults + Result
Else
AllResults = AllResults + "No Match for: " & item
End If
I recommend that you can split the string into long sentences by special symbols, such as , : ? .
Split(Char[])
You can refer to the following code.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = ""
Dim Index As Integer
Dim longStr() As String
Dim str = TextBox3.Text
longStr = TextBox1.Text.Split(New Char() {CChar(":"), CChar(","), CChar("."), CChar("?"), CChar("!")})
Index = 0
For Each TheStr In longStr
If TheStr.Contains(str) Then
RichTextBox1.AppendText(longStr(Index) & vbCrLf)
End If
Index = Index + 1
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "....."
End Sub
End Class
Result:
Try like this:
Dim ArrStr() As String
Dim Index As Integer
Dim TheStr As String
Dim MatchFound As Boolean
MatchFound = False
ArrStr = Split(txtScrape.text," ")
Index = 1
For Each TheStr In ArrStr
If TheStr = Search Then
Console.WriteLine(Index)
MatchFound = True
End If
Index = Index + 1
Next
Console.WriteLine(MatchFound)
Inside the If statement you will get the index there. And MatchFound is the Boolean value if match found.

Encode and Decode VBA Program

in my programming class I have to create a program which allows the user in order to enter a sentence, with the buttons "Encode" and "Decode" as options. So, for "Encode", you have to translate the sentence into Asc numbers (already did this). However, I'm currently stuck on the "Decode" section, for you have to use a For loop and an array to separate the Asc numbers by spaces, then translate them into characters one by one. Here's what I have so far:
Public Class Form1
Dim Message As String
Dim NewMessage As String
Dim Part As String
Dim Part2 As Integer
Dim Letter As String
Dim Length As String
Dim ints() As Integer
Dim intlength As Integer
Private Sub btn_Enter_Click(sender As Object, e As EventArgs) Handles btn_Enter.Click
Message = txt_Message.Text
Length = Message.Length() - 1
If rbn_Encode.Checked = True Then
For Num As Integer = 0 To Length
Letter = Message(Num)
Me.lbl_Code.Text = lbl_Code.Text & Asc(Letter) & " "
Next
End If
If rbn_Decode.Checked = True Then
For Num As Integer = 0 To intlength Step 1
If Message(Num) <> " " Then
Part = Part & Message(Num)
Else
NewMessage = NewMessage & ChrW(Part) & " "
End If
Next
Me.lbl_Code.Text = NewMessage
End If
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
End Class
I've been stuck on this for about 2 week, and I'm still clueless. Thank you for your help and have a wonderful day.
This might seem to veer off the topic of the question, but it all meanders towards a better answer.
OK there are a few issues with your code. Firstly, make sure that "Option Strict" is on - have a look here. This will force you to convert types properly and reduce the potential for problems. Bearing the above in mind,
Dim Length As String
should be
Dim Length As Integer
on to the next bit
Each procedure should have a single responsibility. Your btn_Enter.Click event handler includes code for encoding text and decoding numbers. These should be separated out into their own procedures. In a relatively short bit of code like yours, it's not too much of a problem, but even here, it makes things a little fuzzier. Have a look at the code below. There are more issues, but we'll look at them in a moment. The code below is a bit clearer and more maintainable.
Private Sub btn_Enter_Click(sender As Object, e As EventArgs) Handles btn_Enter.Click
Message = txt_Message.Text
Length = Message.Length() - 1
If rbn_Encode.Checked = True Then
EncodeTextToAscii()
End If
If rbn_Decode.Checked = True Then
DecodeToText()
End If
End Sub
Private Sub DecodeToText()
For Num As Integer = 0 To intlength Step 1
If Message(Num) <> " " Then
Part = Part & Message(Num)
Else
NewMessage = NewMessage & ChrW(Part) & " "
End If
Next
Me.lbl_Code.Text = NewMessage
End Sub
Private Sub EncodeTextToAscii()
For Num As Integer = 0 To Length
Letter = Message(Num)
Me.lbl_Code.Text = lbl_Code.Text & Asc(Letter) & " "
Next
End Sub
Next.
In your code to encode the string as ASCII, you store the resulting data directly in the label lbl_Code's text property. The user interface should never be used as the primary store for data. It's bad practice and potentially allows the user to change data accidentally - in textboxes for example. In the case of a label, it's not to important, but it's far better to get into the good habits.
To store your encoded ASCII numbers, you can use the array ints, but as your code stands, the declaration of ints is just that. There is no space in the array to store data. So, in the Encode procedure, you need to resize ints to the same as the number of characters in the string.
So now we have ..
Private Sub EncodeTextToAscii()
ReDim ints(Length)
For Num As Integer = 0 To Length
Letter = Message(Num)
ints(Num) = Asc(Letter)
Next
End Sub
Finally onto the meat of your question. The Decode procedure can now be written as this ..
Private Sub DecodeToText()
NewMessage = ""
For Each asciiNumber As Integer In ints
NewMessage = NewMessage & ChrW(asciiNumber) & " "
Next
Me.lbl_Code.Text = NewMessage
End Sub
Instead of mucking around getting the length of a loop and getting the ascii number in each element of an array, you can simplyfy it using a For Each statement. You dont need to know the length of the array. It just loops over the whole length. Much easier.
As an excercise, try applying the For Each idea to the Encode procedure. :-)

Detect the sign in number input

how can i detect if the input number in textbox contains "-"
so i can change the output into positive number and
if not contain "-" the output number is become negative
i'm using Vb.net 2010 tnx in advance for who wants to help
Dim output As String
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If getbyte(TextBox1.Text, 0) = Chr(45) Then ' check whether the first character is - or not
output = New String((From c As Char In TextBox1.Text Select c Where Char.IsDigit(c)).ToArray())
else
output="-" & textbox1.text
End If
msgbox (CInt(output))' will give the number
End Sub
Getbyte function to take each character from a string based on the position
Private Function getbyte(ByVal s As String, ByVal place As Integer) As String
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function
if you want to convert the -eve number to positive for calculation you can use
You have couple of options, two of them are:
1) Use StartsWith functions:
If Textbox1.Text.Trim().StartsWith("-"))Then
' It is a negative number
End If
2) If you just need to toggle the number sign, then:
Dim number as Integer = Integer.Parse(Textbox1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Using option2, i get:
Dim txta1 As New TextBox
txta1.Text = "-2"
Dim number As Double = Double.Parse(txta1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Dim s As String = number & " | "
Output: 2 |

Binary Search or Insertion Sort with list view [Visual Basic .net]

Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
Dim midpoint As Integer
If lowindex > highindex Then
MsgBox("Search Failed")
Else
midpoint = (highindex + lowindex) / 2
If temp(midpoint) = Key Then
MsgBox("found at location " & midpoint)
ElseIf Key < temp(midpoint) Then
Call BinarySearch(Key, lowindex, midpoint, temp)
ElseIf Key > temp(midpoint) Then
Call BinarySearch(Key, midpoint, highindex, temp)
End If
End If
End Sub
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim Key As String = txtSearch.Text
Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
Dim lowindex As Integer = 0
Dim highindex As Integer = lstOutput.Items.Count - 1
'Somehow all of the items in Target column must be placed in temp array
Dim temp(Me.lstOutput.Items.Count - 1) As String
' BinarySearch(Key, lowindex, highindex, temp)
End Sub
For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub
Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language
Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myArray(Me.ListView1.Items.Count - 1) As String
Dim i As Integer
' load array
For i = 0 To Me.ListView1.Items.Count - 1
myArray(i) = Me.ListView1.Items(i).Text
Next
' show the results
Dim s As String = ""
For i = 0 To UBound(myArray)
s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
Next
MsgBox(s, MsgBoxStyle.Information, "myArray Contents")
' now go ahead and manipulate the array as needed
' ...
End Sub

Splitting a string based on a set length of characters

MVC 3. Vb.net. Part of my app generates PDF files using Itextsharp. Some strings are too long to go onto the background image correctly. So I basically need to split this string when its over 26 characters long and when it splits it cant split in the middle of a word. from there I will use newline to add the string to the right to the next line... Any ideas that might point me in the right direction.. I did start bulding the function that I will pass the string into test for length and then pass back the string after it finishes but I am stummped after that..
Private Function stringLength(ByVal _string As String) As String
If _string.Length < 26 Then
_string.Split(
End If
End Function
I'm sure there's a million different ways to do this.
You basically need to get all of your words split by the space into a list. After that, you just need to keep checking if the current word plus a space plus the next word reach your threshold or not, and if it does, you move to the next line. Once you have all of your lines, then you rejoin the list into a single string again.
Private Function LimitWidth(ByVal text As String, ByVal maxCharacters As Integer) As String
Dim words As List(Of String) = text.Split(" "c).ToList()
If text.Length < maxCharacters OrElse words.Count = 1 Then
Return text
Else
Dim lines As New List(Of String)
Dim currentLine As String = words(0)
For i As Integer = 1 To words.Count - 1
If (currentLine & " " & words(i)).Length > maxCharacters Then
lines.Add(currentLine)
currentLine = words(i)
If i = words.Count - 1 Then
lines.Add(currentLine)
End If
Else
If i = words.Count - 1 Then
lines.Add(currentLine & " " & words(i))
End If
currentLine &= " " & words(i)
End If
Next
Return String.Join(Environment.NewLine, lines.ToArray())
End If
End Function
To Test:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MessageBox.Show(LimitWidth("This is a really long sentence " & _
"meant to demonstrate how to split " & _
"the words into a confined character length.", 26))
End Sub
It sounds like you are asking for a word wrap function.
Since I feel that it's better to answer in a way that promotes learning than to just give answers, I have for you a link that walks you through the process of using Test Driven Development (TDD) to solve this problem. It just so happens that the word wrap problem is a popular coding kata, and Robert C. Martin wrote a somewhat silly fictional story about a developer being taught how to use TDD to solve the word wrap kata.
The code examples are in Java, but it should be trivial to read and translate.
http://thecleancoder.blogspot.com/2010/10/craftsman-62-dark-path.html
The goofy bits are skip-able. Just jump down to the sentences right before the first code snippet.
I would add to it handling of multiline input text with following:
Private Function LimitWidth(ByVal text As String, ByVal maxCharacters As Integer, SplitSign As String) As String
Dim Output As String = ""
Dim OrgLines As List(Of String) = text.Split(Environment.NewLine).ToList()
For x As Integer = 1 To OrgLines.Count - 1
Dim words As List(Of String) = OrgLines(x).Split(" "c).ToList()
If text.Length < maxCharacters OrElse words.Count = 1 Then
Output += OrgLines(x)
Else
Dim lines As New List(Of String)
Dim currentLine As String = words(0)
For i As Integer = 1 To words.Count - 1
If (currentLine & " " & words(i)).Length > maxCharacters Then
lines.Add(currentLine)
currentLine = words(i)
If i = words.Count - 1 Then
lines.Add(currentLine)
End If
Else
If i = words.Count - 1 Then
lines.Add(currentLine & " " & words(i))
End If
currentLine &= " " & words(i)
End If
Next
Output += String.Join(SplitSign, lines.ToArray())
End If
Next
Return Output
End Function
use:
LimitWidth("your text", 80, Environment.NewLine)