Remove textbox lines contains less value or greather value VB.Net - vb.net

how can i do a code to remove values <1 and values greater than> 80?
Textbox1.Lines
2
11
-1
82
73
11
12
13
14
15
Expected Output:
2
11
73
11
12
13
14
15
Why didn't work.
If TextBox1.Lines.Contains < 1 Then
TextBox1.Lines(0).String.Empty
ElseIf TextBox1.Lines.Contains > 80 Then
TextBox1.Lines(0).String.Empty
End if.

First, let us look up what the .Contains method expects. https://learn.microsoft.com/en-us/dotnet/api/system.string.contains?view=netframework-4.8
Public Function Contains (value As String) As Boolean Ah ha! It expects a string and returns True or False.
Now, let us look at the first line of your code
If TextBox1.Lines.Contains < 1 Then I don't see parenthesis containing a string so the method can't work. You are dealing with strings in a TextBox. .Lines are strings, .Contains expects a string. You can't compare an Integer to a string.
Code Explanation:
Use a StringBuilder. Every time you "change" a string the application must throw away the old string and create an entirely new string. When you are doing this at least 10 times you want to save all that thrashing about by using a StringBuilder which is mutable (changeable).
The string in the line must be converted to an Integer so we can compare it to another Integer. The AndAlso is a short circuit meaning if the first condition is False it doesn't bother checking the second condition. This is a smidge faster.
Private Sub OPCode()
Dim sb As New StringBuilder
For Each line In TextBox1.Lines
If CInt(line) > 1 AndAlso CInt(line) < 80 Then
sb.AppendLine(line)
End If
Next
TextBox2.Text = sb.ToString
End Sub

Related

Extract first two digits that comes after some string in Excel

I have a row with values something like this, How to extract first two digits that come after the text 'ABCD' to another cell, any formula or vba? There may be a few chars in between or sometimes none.
ABCD 10 sadkf sdfas
ABCD-20sdf asdf
ABCD 40
ABCD50 asdf
You can do this with a worksheet formula. No need for VBA.
Assuming you do not need to test for the presence of two digits:
=MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2)
If you need to test for the presence of two digits, you can try:
=IF(ISNUMBER(-RIGHT(MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2),1)),MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2),"Invalid")
In general, it is always a good idea to show some code in StackOverflow. Thus, you show that you have tried something and you give some directions for the answer.
Concerning the first two digits extract, there are many ways to do this. Starting from RegEx and finishing with a simple looping of the chars and checking each one of them.
This is the loop option:
Public Function ExtractTwoDigits(inputString As String) As Long
Application.Volatile
Dim cnt As Long
Dim curChar As String
For cnt = 1 To Len(inputString)
curChar = Mid(inputString, cnt, 1)
If IsNumeric(curChar) Then
If Len(ExtractTwoDigits) Then
ExtractTwoDigits = ExtractTwoDigits & curChar
Exit Function
Else
ExtractTwoDigits = curChar
End If
End If
Next cnt
ExtractTwoDigits = -1
End Function
Application.Volatile makes sure that the formula recalculates every time;
-1 is the answer if no two digits exist in the inputString;
IsNumeric checks whether the string inside is numeric;
As a further step, you may try to make the function a bit robust, extracting the first 1, 3, 4 or 5 digits, depending on a parameter that you put. Something like this =ExtractTwoDigits("tarato123ra2",4), returning 1232.
RegEx Version:
Public Function GetFirstTwoNumbers(ByVal strInput As String) As Integer
Dim reg As New RegExp, matches As MatchCollection
With reg
.Global = True
.Pattern = "(\d{2})"
End With
Set matches = reg.Execute(strInput)
If matches.Count > 0 Then
GetFirstTwoNumbers = matches(0)
Else
GetFirstTwoNumbers = -1
End If
End Function
You have to enable Microsoft Regular Expressions 5.5 under extras->references. The pattern (\d{2}) matches 2 digits, return value is the number, if not existing -1.
Note: it only extracts 2 successive numbers.
If you place this function into a module, you can use it like normal formula.
Here a great site to to get into regEx.

check if string contains specific integer

I have a grid view that has a column containing strings (Middle column).
On the rowDataBound event I want to loop through the column looking for the integer it contains and then display a value in the first column.
I know that the integer range will be 1 to 63 so I can use a FOR loop to loop through the numbers. Here is what I have so far.
For x As Integer = 1 To 63
If CType(e.Row.Cells(2).FindControl("lblTagName"), Label).Text Then
End If
Next
The problem I am having is using contains. I cant use the following as it would also be true for the number 1, 10, 11 etc when x = 1.
For x As Integer = 1 To 63
If CType(e.Row.Cells(2).FindControl("lblTagName"), Label).Text.Contains(x) Then
End If
Next
How do I make sure it only gets one result per number? i.e x = 6 would return UMIS.75OPTR6GROSSMARGIN.F_CV and not all the other strings that contain the number 6.
UPDATE - based on some answers I may not of explained this very well. I want to loop through the gridview and if the number 1 is found and only the number 1 in the second column, not 10 etc then I want to display "Run 1" in the first column. So when x = 10 it will show "Run 10" and so on.
UPDATE 2 - its definatley my explanation, apologies.
The resultant grid view would look like this.
The order of the second column is not set and is not in order.
You'd have to check the entire text of the label to determine whether it is only 1, and not 10, 11, 12, 13, ... as well.
Also, in this case you should use DirectCast rather than CType. CType is only used when converting to different types that include conversion operators, here you are always dealing with a label.
For x As Integer = 1 To 63
If String.Equals(DirectCast(e.Row.Cells(2).FindControl("lblTagName"), Label).Text, "UMIS.75OPTR" & x & "GROSSMARGIN.F_CV", StringComparison.OrdinalIgnoreCase) Then
'Do your stuff.
End If
Next
You might want to think if doing it the other way around. Get the list of numbers in your string with a regular expression match.
Dim s As String = "asd12asdasd.sdf3sdf"
For Each m As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(s, "[\d]*")
If m.Success AndAlso Not String.IsNullOrEmpty(m.Value) Then
' m.Value
End If
Next
With that list of number, you can check if it's between 1 and 63.
If your string have the same suffix/prefix, just remove them to show you what the number is.
Dim s As String = "UMIS.75OPTR12GROSSMARGIN.F_CV"
Dim number As String = s.Replace("UMIS.75OPTR", "").Replace("GROSSMARGIN.F_CV", "")
Go backwards in a Do Until Loop:
Dim bolFoundMatch As Boolean = False
Dim intCursor As Integer = 63
Do Until (bolFoundMatch OrElse intCursor = 0)
If CType(e.Row.Cells(2).FindControl("lblTagName"), Label).Text.Contains(intCursor) Then
'Anything you want to do when you find your match.
'This will ensure your loop exits.
bolFoundMatch = True
End If
intCursor -= 1
Loop

How do I check if ticket number is formatted using a function?

I would like my function to follow some convention to check if my ticket number needs formatting or not.
If the convention is not met, then I would like to make some changes to the ticket number.
Ticket number 19K3072216 needs to be formatted to this 19-K3-07-002216 because it does not meet the following conditions.
My function should do the following.
Check if the 1st 2 digits has a value 0 - 9 (numeric)
Check if the 3rd digit has a value of A to Z
Check if the 4th digit has a value 0 - 9 (numeric)
Check if the 5th and 6th digits has a date value (e.g.2 digit year - 17, 90, 15 etc)
Check if the next 6 digits i.e. 7th - 12th digits are numeric.
Because ticket number 19K3072216 does not meet the above conditions, I would like my function to format it to look like this 19-K3-07-002216
The string strTicketNumber should return formatted ticket number 19-K3-07-002216
My vb.net function
Public Class Ticket_Code
Public Shared Sub main()
Dim strTicketNumber As String = FixTicketNumber("19K3072216")
End Sub
Public Shared Function FixCaseNumber(ByVal astrCaseNumber As String) As String
Dim strCaseNumber As String = Replace(astrCaseNumber, "-", "")
'Determine if ticket number is formatted
How do I do this?
'If ticket number is formatted add 2 zeros
'How do I do this?
'Else return unchanged
'If ticket number is already formatted, just returned the number (original number)
Return strCaseNumber
End Function
End Class
It will really depend on your input and how different from the example it can be.
For instance will invalid input always be in the same format 19K3072216or is there the chance it will be all digits, all letters, less/more than 10 characters long etc. All of these rules need to be considered and handled as necessary.
If the input will be from a user, never trust it and always assume it is the furthest from valid as possible. If the app can handle that case it can handle everything else
Something like this should get you started:
Public Sub Main()
Dim strTicketNumber As String = FixTicketNumber("19-K3-07-002216") ' or 19K3072216
Console.WriteLine(strTicketNumber)
Console.ReadKey()
End Sub
Private Function FixTicketNumber(p1 As String) As String
Dim fixed As String = ''
Dim valid As Boolean = checkTicketNumber(p1)
If valid Then
Return p1 ' Ticket number is valid, no transformation needed
Else
'Assume invalid input will always be 10 characters (e.g. 19K3072216)
'Split the input and Step through each rule one at a time
'returning the necessary result/format string as you go
'#1 Check if the 1st 2 digits has a value 0 - 9 (numeric)
Dim ruleOne As String = p1.Substring(0, 2)
'perform isNumeric, concatenate to fixed if everything is ok
'fixed += ruleOne+"-"
'#2 Check if the 3rd digit has a value of A to Z
Dim ruleTwo As String = p1.Substring(3, 1)
'check if its a letter, concatenate to fixed if everything is ok
'... same for all the rules
End If
End Function
Private Function checkTicketNumber(p1 As String) As Boolean
'See if the input matches the rules
'Check if the 1st 2 digits has a value 0 - 9 (numeric)
'Check if the 3rd digit has a value of A to Z
'Check if the 4th digit has a value 0 - 9 (numeric)
'Check if the 5th and 6th digits has a date value (e.g.2 digit year - 17, 90, 15 etc)
'Check if the next 6 digits i.e. 7th - 12th digits are numeric.
Dim pattern As String = "\d{2}-[A-Z]\d-\d{2}-\d{6}"
Dim match As Match = Regex.Match(p1, pattern)
Return match.Success
End Function
It is hard to produce a fully working solution as there are too many unknowns about the input as an outsider.

Count lines before specified string of Text File? In VB

is there a way to count the amount of lines before a specific line / string in a text file.
For Example:
1
2
3
4
5
6
7
8
9
Say i want to count the amount of line before '8'...
How would i do that?
thanks!
Hope that this actually you are looking for,
it will read all lines from a file specified. then find the IndexOf particular line(searchText) then add 1 to it will gives you the required count since index is0based.
Dim lines = File.ReadAllLines("f:\sample.txt")
Dim searchText As String = "8"
msgbox(Array.IndexOf(lines, searchText) + 1)
Here's another example using List.FindIndex(), which allows you to pass in a Predicate(T) to define how to make a match:
Dim fileName As String = "C:\Users\mikes\Documents\SomeFile.txt"
Dim lines As New List(Of String)(File.ReadAllLines(fileName))
Dim index As Integer = lines.FindIndex(Function(x) x.Equals("8"))
MessageBox.Show(index)
In the example above, we're looking for an exact match with "8", but you can make the predicate match whatever you like for more complex scenarios. Just make the function (the predicate) return True for what you want to be a match.
For example, a line containing "magic":
Function(x) x.ToLower().Contains("magic")
or a line that begins with a "FirstStep":
Function(x) x.StartsWith("FirstStep")
The predicate doesn't have to be a simple string function, it can be as complex as you like. Here's one that will find a string that ends with "UnicornFarts", but only on Wednesday and if Notepad is currently open:
Function(x) DateTime.Today.DayOfWeek = DayOfWeek.Wednesday AndAlso Process.GetProcessesByName("notepad").Length > 0 AndAlso x.EndsWith("UnicornFarts")
You get the idea...
Using a List, instead of an Array, is good for situations when you need to delete and/or insert lines into the contents before writing them back out to the file.

How to read first 2 number of every line in listbox vb . Net

I have listbox has lines like this
12345678%32=5
4663578877fg
6883346899
,,,etc
How can I get the first two number of every line to be like this
12
46
68
BTW the listbox has only numbers in first of every line
Thanks!
myListBox.Items.Add("1234")
myListBox.Items.Add("567")
myListBox.Items.Add("890")
For position As Integer = 0 To myListBox.Items.Count - 1
myListBox.Items(position) = CStr(myListBox.Items(position)).Substring(0, 2)
Next
EDIT
We can use the RichTextBox.Lines property that returns a array of String. Each String in the array represents a line in the RichTextBox. If you want to store the first two digits in an array, you can try :
Dim intValues(Convert.ToInt32(RichTextBox1.Lines.Length)) As Integer 'Stores the digits
For position As Integer = 0 To Convert.ToInt32(RichTextBox1.Lines.Length) - 1
intValues(position) = Convert.ToInt32(RichTextBox1.Lines(position).Substring(0, 2))
Next