VB.NET RichTextBox and TextBox Separation - vb.net

For my company, we receive our time sheets in the following format
Name:Hours
Name:Hours
Name:Hours
I have the Timesheet.txt loading into the RichTextBox1 fine, but, I want when I click a button to load them into two different textboxes. I want the Names to load into TextBox1 and Hours to load into TextBox2
Then it deletes the line. It will go onto the next line when I click the button again.
Any help?

Simple, but will do:
Dim sInput As String = "Name:10"
Dim sSplitArray() As String = sInput.Split(New Char() {":"c})
Dim sName As String = sSplitArray(0)
Dim sHours As String = sSplitArray(1)
String's Split function splits a string up by the character you pass to it.
So if you have this:
sInput = "Name:10:Zebra:Kazaam"
When you split that string by the ":" separator, it will give you an array with:
Name
10
Zebra
Kazaam

Hope that this will give the complete solution for your problem
Dim x, y As Integer
Dim textbox1() As TextBox
x = 430
y = 265
Dim str As String
Dim result(), output(1) As String'str=RitchText1.text 'load input string to str
result = str.Split(System.Environment.NewLine) ' split into array based on new line
For i As Integer = 0 To result.Length - 1 'execute up to array limit
output = result(i).Split(":") 'split again based on :
textbox1(i).Text = output(0) 'Name part into dynamic textbox 1
textbox1(i).Location = New Point(x, y)
textbox1(i + 1).Text = output(1) 'Name part into dynamic textbox 2
textbox1(i + 1).Location = New Point(x + 40, y)
Me.Controls.Add(textbox1(i))
textbox1(i).Visible = True
Me.Controls.Add(textbox1(i + 1))
textbox1(i + 1).Visible = True
y = y + 20
Next

Related

Does the textbox that is generated when creating a detail view not count as a textbox?

My code searches for certain numbers in textboxes and replaces them. The code however does not change the number if it is in a textbox that is created from a detail view(see figure 1). Do these not count as textboxes?
Figure 1
Dim Totalsheets As Integer
Dim target_text As String
Dim FirstPage As Integer
Dim replace_text As String
Dim result As String
Dim n As Integer 'count No. of text frames changed
Dim i As Integer 'count views for the sheet
Dim x As Integer 'takes the value of the first page of the old config
Dim y As Integer 'takes the value of the total number of sheets of the old config
Dim z As Integer 'takes the value of the number that needs to be added to update the zoning
Dim a As String 'takes the value of the letter found in the zoning box
Dim b As Integer
n = 0
Set osheets = odoc.Sheets
Set osheets = osheets.Item("DRAFT") 'makes sure only sheet "DRAFT" is edited
Set oViews = osheets.Views
Totalsheets = Totalsheets1.Value 'draws value from the textbox
FirstPage = FirstPage1.Value 'draws value from the textbox
For i = 3 To oViews.Count 'scans through all views in sheet
Set oView = oViews.Item(i)
Set oTexts = oView.Texts
For Each SrcText In oTexts 'scans through all text in view
x = FirstPage
y = Totalsheets
b = x + y
Do Until x = b + 1
z = x + Totalsheets
a = "A"
Do Until a = "[" 'goes from A to Z
result = SrcText.Text
target_text = " " & x & a 'gets space in front and letter at back to ensure only zone box are updated
replace_text = " " & z & a
If InStr(result, target_text) Then
result = Replace(result, target_text, replace_text)
SrcText.Text = result
n = n + 1
End If
a = Chr(Asc(a) + 1)
Loop
x = x + 1
Loop
Next
Next
Although the detail view identifier is a DrawingText, it does not belong to the DrawingTexts-collection.
You could access the DrawingText by searching in the view.
Better would be to rename the property of the view.
EDIT:
Example for using the (slower) selection:
Set oSel = oDoc.Selection
oSel.Clear
oSel.Add oView
oSel.Search "CATDrwSearch.DrwText,sel"
for i = 1 to oSel.Count2
Set oDrwText = oSel.Item2(i).Value
'do something with the text
next

Splitting string every 100 characters not working

I am having a problem where I just can't seem to get it to split or even display the message. The message variable is predefined in another part of my code and I have debugged to make sure that the value comes through. I am trying to get it so that every 100 characters it goes onto a new line and with every message it also goes onto a new line.
y = y - 13
messagearray.AddRange(Message.Split(ChrW(100)))
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0
Label1.Text = Label1.Text & vbCrLf & messagefin
Label1.Location = New Point(5, 398 + y)
You can use regular expression. It will create the array of strings where every string contains 100 characters. If the amount of remained characters is less than 100, it will match all of them.
Dim input = New String("A", 310)
Dim mc = Regex.Matches(input, ".{1,100}")
For Each m As Match In mc
'// Do something
MsgBox(m.Value)
Next
You can use LINQ to do that.
When you do a Select you can get the index of the item by including a second parameter. Then group the characters by that index divided by the line length so, the first character has index 0, and 0 \ 100 = 0, all the way up to the hundredth char which has index 99: 99 \ 100 = 0. The next hundred chars have 100 \ 100 = 1 to 199 \ 100 = 1, and so on (\ is the integer division operator in VB.NET).
Dim message = New String("A"c, 100)
message &= New String("B"c, 100)
message &= New String("C"c, 99)
Dim lineLength = 100
Dim q = message.Select(Function(c, i) New With {.Char = c, .Idx = i}).
GroupBy(Function(a) a.Idx \ lineLength).
Select(Function(b) String.Join("", b.Select(Function(d) d.Char)))
TextBox1.AppendText(vbCrLf & String.Join(vbCrLf, q))
It is easy to see how to change the line length because it is in a variable with a meaningful name, for example I set it to 50 to get the output
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
You can use String.SubString to do that. Like this
Dim Message As String = "your message here"
Dim MessageList As New List (Of String)
For i As Integer = 0 To Message.Length Step 100
If (Message.Length < i + 100) Then
MessageList.Add(Message.SubString (i, Message.Length - i)
Exit For
Else
MessageList.Add(Message.SubString (i, 100))
End If
Next
Dim k = MessageList.Count - 1
...
Here is what your code produced with a bit of clean up. I ignored the new position of the label.
Private Sub OpCode()
Dim messagearray As New List(Of String) 'I guessed that messagearray was a List(Of T)
messagearray.AddRange(Message.Split(ChrW(100))) 'ChrW(100) is lowercase d
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0 'Why reset k? It falls out of scope at End Sub
Label1.Text = Label1.Text & vbCrLf & messagefin
End Sub
I am not sure why you think that splitting a string by lowercase d would have anything to do with getting 100 characters. As you can see the code reversed the order of the list items. It also added a blank line between the existing text in the label (In this case Label1) and the new text.
To accomplish your goal, I first created a List(Of String) to store the chunks. The For loop starts at the beginning of the input string and keeps going to the end increasing by 10 on each iteration.
To avoid an index out of range which would happen at the end. Say, we only had 6 characters left from start index. If we tried to retrieve 10 characters we would have an index out of range.
At the end we join the elements of the string with the separated of new line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BreakInto10CharacterChunks("The quick brown fox jumped over the lazy dogs.")
End Sub
Private Sub BreakInto10CharacterChunks(input As String)
Dim output As New List(Of String)
Dim chunk As String
For StartIndex = 0 To input.Length Step 10
If StartIndex + 10 > input.Length Then
chunk = input.Substring(StartIndex, input.Length - StartIndex)
Else
chunk = input.Substring(StartIndex, 10)
End If
output.Add(chunk)
Next
Label1.Text &= vbCrLf & String.Join(vbCrLf, output)
End Sub
Be sure to look up String.SubString and String.Join to fully understand how these methods work.
https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8
and https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8

Remove a line of text where the cursor is positioned

All my below code remove all blank lines from TextBox.
But I want the cursor pointed line to get removed when clicked on button.
'First method
TextBox2.Lines = TextBox2.Lines.Where(Function(l) Not String.IsNullOrWhiteSpace(l)).ToArray()
Dim count = TextBox2.Lines.Length
'Second method
Dim tmp() As String = TextBox2.Text.Split(CChar(vbNewLine))
TextBox2.Clear()
For Each line As String In tmp
If line.Length > 1 Then
TextBox2.AppendText(line & vbNewLine)
End If
Next
'Third method
Dim SearchIn = Me.TextBox2.Text
Dim sb As StringBuilder = New StringBuilder(SearchIn)
Me.TextBox2.Text = sb.Replace(vbCrLf + vbCrLf, vbCrLf).ToString
'Fourth method
TextBox2.Text = Regex.Replace(TextBox2.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?)", "${Text} ") + "/n"
TextBox2.Text = Replace(TextBox2.Text, vbCrLf & vbCrLf, vbCrLf)
To remove a line of text from a TextBoxBase derived control (TextBox, RichTextBox), you first have to identify the correct line.
You can't use the .Lines property if the Text is wrapped, because it will return the line number relative to the unwrapped text.
You can get the current wrapped line with GetLineFromCharIndex(). The Integer parameter is the current caret position, referenced by the SelectionStart property.
The first character index of this line is retured by GetFirstCharIndexFromLine().
Then, find the current line lenght, identifying the first line feed. Add the lenght of the line feed symbol(s) to include them in the computed lenght.
Note that TextBox controls use Environment.Newline to generate a line feed ("\r\n"), while RichTextBox controls use only a line feed ("\n").
This will remove any line where the caret is currently positioned:
(If you just want to allow blank lines to be removed, check whether the line lenght is < 3).
Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim CurrentLine As Integer = TextBox2.GetLineFromCharIndex(CurrentPosition)
Dim LineFirstChar As Integer = TextBox2.GetFirstCharIndexFromLine(CurrentLine)
Dim LineLenght As Integer = TextBox2.Text.
IndexOf(Environment.NewLine, LineFirstChar) - LineFirstChar +
Environment.NewLine.Length
If LineLenght <= 0 Then Return
TextBox2.Select(LineFirstChar, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If(CurrentPosition < TextBox2.Text.Length, LineFirstChar, TextBox2.Text.Length)
TextBox2.Focus()
This will instead remove the whole paragraph that contains the caret:
Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim ParagraphFirstIndex As Integer = TextBox2.Text.
LastIndexOf(Environment.NewLine, CurrentPosition) +
Environment.NewLine.Length
Dim LineFeedPosition As Integer = TextBox2.Text.IndexOf(Environment.NewLine, ParagraphFirstIndex)
LineFeedPosition = If(LineFeedPosition > -1, LineFeedPosition + Environment.NewLine.Length, TextBox2.Text.Length)
Dim LineLenght As Integer = LineFeedPosition - ParagraphFirstIndex
If LineLenght <= 0 Then Return
TextBox2.Select(ParagraphFirstIndex, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If((CurrentPosition < TextBox2.Text.Length), ParagraphFirstIndex, TextBox2.Text.Length)
TextBox2.Focus()

How can I seperate the values in the textbox to show in different labels using button?

i want to be able to separate the values in a textbox and display the separated values in different labels using a button
this is what i want to happen:
input "Ac2O3" on textbox
Be able to separate "Ac", "2", "O", and "3".
Show the separated values in different textboxes using a button
im using visual basic 2012
im sorry im still new to this
thanks in advance!!
You can access different character of the string with the index.
Dim input As String = "Ac2O3"
Dim part1 As String = input(0) & input(1)
Dim part2 As String = input(2)
Dim part3 As String = input(3)
Dim part4 As String = input(4)
If you don't know how to handle the button event or how to display text in a textbox, that would be different questions.
This code creates a structure called Element to make the results from the function clearer - add this to your main class that the function is going to be placed in. The main function takes a string as it's input and produced a list of structures of Element as it's output. There probably are shorter ways to do this, but I'm a fairly basic programmer who likes a puzzle - hope this helps - Dont forget to accept the answer by clicking on the tick. If you have any queries please dont hesitate to ask
Structure Element
Dim symbol As String
Dim elementCount As Int16
End Structure
Function ParseFormula(ByVal compoundString As String) As List(Of Element)
Dim tempParseFormula = New List(Of Element)
Dim firstLetter As String = "[A-Z]"
Dim secondLetter As String = "[a-z]"
Dim number As String = "[0-9]"
Dim tempElementCount As String = ""
Dim maxIndex As String = compoundString.Length - 1
Dim i As Integer = 0
Dim parsedElement As New Element
While i <= maxIndex
Dim tempChar As String = compoundString(i)
Select Case True
Case tempChar Like firstLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like secondLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like number
tempElementCount = tempElementCount & tempChar
End Select
If i = maxIndex Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
Exit While
End If
i += 1
If compoundString(i) Like firstLetter Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
End If
End While
Return tempParseFormula
End Function

I have three variables declared as strings, is there a way to randomly choose one? [duplicate]

This question already has answers here:
How can I randomly select one of three strings?
(2 answers)
Closed 8 years ago.
I have three strings, sUpperCase, sLowerCase and sNumbers. Each have either lower characters, upper characters or numbers. I need to know how to randomly choose one of these strings. I have thought maybe by assigning them a number but I am not sure how do to this without overriding the text inside of them. Maybe even an array but I'm not sure how to do this either. Can anybody help please?
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
ANSWER:
Function GeneratePassword() As String
'
' Declare two strings as the characters which the password can be created from
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
' Create a new random.
' Random is something which gets a random set of characters from a string.
Dim random As New Random
'
' Create sPassword as a new stringbuilder
' A stringbuilder is simply a class which builds a string from multiple characters
Dim sPassword As New StringBuilder
' Not random enough
'For i As Integer = 1 To 4
' Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
' sPassword.Append(sUpperCase.Substring(idxUpper, 1))
' Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
' sPassword.Append(sNumbers.Substring(idxNumber, 1))
' Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
' sPassword.Append(sLowerCase.Substring(idxLower, 1))
'Next
' Random select Upper, lower or numeric
' Check for a max number of this(three if's to check for which one it was, might need or in if)
' If yes randomly select another one
' If no get random char from that type
' Add to password
' Is the password complete?
' If yes return password, if not repeat
Dim iCountUpper As Integer = 0
Dim iCountLower As Integer = 0
Dim iCountNumber As Integer = 0
Do Until sPassword.Length = 10
'Needed help for this bit
Dim x = New Random(Now.GetHashCode)
Dim y = {"sLowerCase", "sUpperCase", "sNumbers"}
Dim z = y(x.Next(0, y.Length))
If z.Contains("sLowerCase") And iCountUpper < 4 Then
Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
sPassword.Append(sUpperCase.Substring(idxUpper, 1))
iCountUpper = iCountUpper + 1
ElseIf z.Contains("sUpperCase") And iCountLower < 4 Then
Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
sPassword.Append(sLowerCase.Substring(idxLower, 1))
iCountLower = iCountLower + 1
ElseIf z.Contains("sNumbers") And iCountNumber < 2 Then
Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
sPassword.Append(sNumbers.Substring(idxNumber, 1))
iCountNumber = iCountNumber + 1
Else
End If
Loop
'
' Return the password as a string
Return sPassword.ToString
End Function
You could do something like this:
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
Dim x = New Random(Now.GetHashCode)
Dim y = {sLowerCase, sUpperCase, sNumbers}
Dim z = y(x.Next(0, y.Length))
Debug.Print(z)
Dim strings = {"qwertyuiopasdfghjklzxcvbnm", "MNBVCXZLKJHGFDSAPOIUYTREWQ", "1234567890"}
Dim selected As String
Dim Generator As System.Random = New System.Random()
selected = strings(Generator.Next(0, strings.GetUpperBound(0)))
Create an array with your strings:
Dim array As String() = New String() {sLowerCase, sUpperCase, sNumbers}
Use Random class to generate random number between 0 and the array lenght:
Dim random As Random = New Random(DateTime.Now.Ticks)
Dim randomChoose As String = array(random.Next(0, array.Length - 1))
Select a random char:
Dim ch As Char = randomChoose(random.Next(0, randomChoose.Length - 1))