How to make a vertical ruler of orientation with the same number of imported text lines Vb.net

Asked

Viewed 44 times

0

I’m building a text editor and I need to make a vertical ruler with the same number of lines of imported text. I already know how to obtain the number of lines of the imported text but I did not find any solution to make a vertical ruler with the same number of lines as the imported text. Current code only shows numbers up to 20 and text has more lines as shown in the image ímagem da aplicaçao com o codigo actual this is the code I use to get the number of lines

Imports System.IO

Public Class Form1
Dim datax = DateAndTime.Now
Dim time As DateTime = DateTime.Now
Dim format As String = "d M yyyy d HH:mm"
Dim lineCount As Integer

Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CopyToolStripMenuItem.Click
    ' Ensure that text is selected in the text box.   
    If TextBox1.SelectionLength > 0 Then
        ' Copy the selected text to the Clipboard.
        TextBox1.Copy()
    End If
End Sub

Private Sub PastToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PastToolStripMenuItem.Click
    ' Determine if there is any text in the Clipboard to paste into the text box.
    If Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) = True Then
        ' Determine if any text is selected in the text box.
        If TextBox1.SelectionLength > 0 Then
            ' Ask user if they want to paste over currently selected text.
            If MessageBox.Show("Do you want to paste over current selection?", _
                "Cut Example", MessageBoxButtons.YesNo) = DialogResult.No Then
                ' Move selection to the point after the current selection and paste.
                TextBox1.SelectionStart = TextBox1.SelectionStart + _
                    TextBox1.SelectionLength
            End If
        End If
        ' Paste current text in Clipboard into text box.
        TextBox1.Paste()
    End If
End Sub

Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CutToolStripMenuItem.Click
    ' Ensure that text is currently selected in the text box.   
    If TextBox1.SelectedText <> "" Then
        ' Cut the selected text in the control and paste it into the Clipboard.
        TextBox1.Cut()
    End If
End Sub

Private Sub UndoToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UndoToolStripMenuItem.Click
    ' Determine if last operation can be undone in text box.   
    If TextBox1.CanUndo = True Then
        ' Undo the last operation.
        TextBox1.Undo()
        ' Clear the undo buffer to prevent last action from being redone.
        TextBox1.ClearUndo()
    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim a As String
    Dim b As String
    a = TextBox2.Text
    b = InStr(TextBox1.Text, a)
    If b Then
        TextBox1.Focus()
        TextBox1.SelectionStart = b - 1
        TextBox1.SelectionLength = Len(a)
    Else
        MsgBox("No words")
    End If

    Dim result As DialogResult = MessageBox.Show("Confirm Replace?", _
                          "Title", _
                          MessageBoxButtons.YesNo)

    If (result = DialogResult.OK) Then
        'Update data here
    Else
        'Nothing
    End If

    Dim str As String
    str = TextBox2.Text
    If str.Contains(TextBox2.Text) = True Then
        MsgBox("Your Word Its Present In This Text " & ("(") & TextBox2.Text & ")")

        TextBox1.Text = TextBox1.Text.Replace(TextBox2.Text, TextBox3.Text)
    Else
        MsgBox("Your Word Its Not Present In This Text " & ("(") & TextBox2.Text & ")")
    End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim a As String
    Dim b As String
    a = TextBox2.Text
    b = InStr(TextBox1.Text, a)
    If b Then
        TextBox1.Focus()
        TextBox1.SelectionStart = b - 1
        TextBox1.SelectionLength = Len(a)
    Else
        MsgBox("No words")
    End If
    'Dim counter as Integer
    'Create a string array and store the contents of the Lines property.
    ' Dim tempArray() As String
    ' tempArray = TextBox1.Lines

    'Loop through the array and send the contents of the array to debug window.
    ' For counter = 0 To tempArray.GetUpperBound(0)

    'TextBox1.Text = tempArray(counter)
    'Next
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    SelecionarLinha2()
    TrocarLinha2PorLinha1()
End Sub
Private Sub SelecionarLinha2()

    ' Primeiro é necessário verificar se há pelo menos duas linhas.
    If TextBox1.Lines.Count > 1 Then
        ' Seleciona trecho do texto do controle começando no
        ' primeiro caractere da segunda linha (lineNumber=1).
        TextBox1.Select(TextBox1.GetFirstCharIndexFromLine(1), TextBox1.Lines(1).Length)
        ' Se o foco não for enviado para o controle TextBox, a seleção não aparecerá.
        TextBox1.Focus()
    End If

End Sub

Private Sub TrocarLinha2PorLinha1()

    ' Primeiro é necessário verificar se há pelo menos duas linhas.
    If TextBox1.Lines.Count > 1 Then
        Dim troca As String
        ' Quando a propriedade Lines é criada automaticamente a partir
        ' do texto digitado no controle, o array retornado por ela é
        ' apenas uma cópia somente leitura das linhas do controle,
        ' então, o texto não pode ser alterado diretamente na propriedade,
        ' por isso é necessário usar um array temporário.
        Dim linhas() As String = TextBox1.Lines

        ' Troca a segunda linha pela primeira linha.    
        troca = linhas(1)
        linhas(1) = linhas(0)
        linhas(0) = troca

        ' Devolve o array modificado para o controle.    
        TextBox1.Lines = linhas
    End If

End Sub

Private Sub SelecionarLinha2_JeitoAntigo()

    Dim posQuebraDeLinha As Integer = -1
    Dim firstCharIndex As Integer = -1
    Dim lineTwoLength As Integer = 0

    ' Busca pela quebra de linha da primeira linha.
    posQuebraDeLinha = TextBox1.Text.IndexOf(vbCrLf)
    If posQuebraDeLinha < 0 Then Return
    ' Índice do primeiro caractere da segunda linha.
    firstCharIndex = posQuebraDeLinha + 2   '2 = Len(vbCrLf)

    ' Busca pela quebra de linha da segunda linha.
    posQuebraDeLinha = TextBox1.Text.IndexOf(vbCrLf, firstCharIndex)
    If posQuebraDeLinha < 0 Then posQuebraDeLinha = TextBox1.TextLength

    ' Calcula o comprimento do texto na segunda linha.
    lineTwoLength = posQuebraDeLinha - firstCharIndex

    TextBox1.Select(firstCharIndex, lineTwoLength)
    TextBox1.Focus()
End Sub

Private Sub TrocarLinha2PorLinha1_JeitoAntigo()

    Dim troca As String
    ' Divide o texto usando a sequência de CarriageReturn (13) + LineFeed (10)
    ' como separador, resultando em um array em que cada item é uma linha.
    Dim linhas() As String = TextBox1.Text.Split(vbCrLf)

    If linhas.Count > 1 Then
        troca = linhas(1)
        linhas(1) = linhas(0)
        linhas(0) = troca

        ' Junta de volta as linhas do array, usando de novo a sequência
        ' de CarriageReturn (13) + LineFeed (10) como separador.
        TextBox1.Text = String.Join(vbCrLf, linhas)
    End If

End Sub

Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
    OpenFileDialog1.Title = "Open Text File"
    OpenFileDialog1.InitialDirectory = "C:\"
    OpenFileDialog1.ShowDialog()

    Dim textFile As StreamReader

    textFile = File.OpenText(OpenFileDialog1.FileName)
    TextBox1.Text = textFile.ReadToEnd()

    textFile.Close()
End Sub

Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
    TextBox1.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
    lineCount = TextBox1.Lines.Count
End Sub

Public Function RemoveAcentos(ByVal texto As String) As String
    Dim charFrom As String = "ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ"
    Dim charTo As String = "SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy"
    For i As Integer = 0 To charFrom.Length - 1
        texto = Replace(texto, charFrom(i), charTo(i))
    Next
    Return texto
End Function

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    TextBox1.Text = RemoveAcentos(TextBox1.Text.ToString)
End Sub

Private Sub BackgroundColorToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BackgroundColorToolStripMenuItem.Click
    ColorDialog1.ShowDialog()
    TextBox1.BackColor = ColorDialog1.Color
End Sub

Private Sub FontToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FontToolStripMenuItem.Click
    FontDialog1.ShowDialog()
    TextBox1.Font = FontDialog1.Font
End Sub

Private Sub FontColorToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FontColorToolStripMenuItem.Click
    ColorDialog2.ShowDialog()
    TextBox1.ForeColor = ColorDialog2.Color
End Sub

Private Sub InsertDateAndTimeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles InsertDateAndTimeToolStripMenuItem.Click
    'TextBox1.Text &= Environment.NewLine & time.ToString(format)
    TextBox1.Text = TextBox1.Text.Insert(0, time.ToString(format) + vbNewLine)
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Me.Text = time.ToString(format)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Timer1.Start()
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                             Handles TextBox1.TextChanged
    SyncLineNumbers()
    Dim newHeight As Integer = ListBox1.ItemHeight * ListBox1.Items.Count
    If newHeight > Me.Height Then
        ListBox1.Height = newHeight
        TextBox1.Height = newHeight
    End If
    ListBox1.SelectedIndex = TextBox1.GetLineFromCharIndex(TextBox1.SelectionStart)
End Sub

Private Sub SyncLineNumbers()
    If TextBox1.Lines.Count <> ListBox1.Items.Count Then
        Do While TextBox1.Lines.Count > ListBox1.Items.Count
            ListBox1.Items.Add((ListBox1.Items.Count + 1).ToString)
        Loop

    End If
End Sub
End Class

1 answer

0


Use a For-Next flow control framework. The code inside the for-next block will run X times according to the number of lines found in the textbox1. And for each time it is executed, the variable numeroLine will take on the next numerical value. So the first time it’s worth 1, the second 2 and so on.

Ex:

For numeroLinha As Integer = 1 To TextBox1.Lines.Count
    'use o numeroLinha na sua lógica. 
Next
  • thanks but how can I draw them vertically on a gropbox?

  • to help you in the visual part I would need to see better the structure of your form has no way to post more parts of the project?

  • Yes of course I will edit to post the code

  • in fact this was the attempt I made but only shows the numbers until 20 I will edit to post the image too

  • I’ve actually figured out what the mistake is and that it doesn’t count the empty lines and I need it to count the empty lines as well

Browser other questions tagged

You are not signed in. Login or sign up in order to post.