We help IT Professionals succeed at work.
Get Started

RichTextBox format line by button click vb.net 2010

Last Modified: 2015-03-02
Hi Experts,

I'm trying writing to write a winform app with a RTB and button. The button follows the cursor/caret up or down depending on carriage return (which works great thanks to the mighty kaufmed from previous question... Previous Question

The purpose of the button is to format whatever text is on same line as button.
for example: if i want all the text on line 5 to change color to GREEN, then pressing this button will do so. and not continue on another line.

I found the code beow (from a google search) and inserted into my button click, which works great if I don't add Label1.Text in line 2 / 4... works with array (actual number).

1    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
2    RichTextBox1.SelectionStart = RichTextBox1.Text.IndexOf(RichTextBox1.Lines(Label1.Text))  'Sets the selection 3    length as the length of the line 3. At this point, we have now set the start and end positions of the selection.
4    RichTextBox1.SelectionLength = RichTextBox1.Lines(Label1.Text).Length
5    RichTextBox1.SelectionColor = Color.Green   'Sets the color of the selected text to Green.
7    End Sub

Open in new window

The ERROR I'm getting is
Message=Index was outside the bounds of the array.

because Label1 shows line numbers... I thought it would be easy to pass it through a label.
Watch Question
Distinguished Expert 2017
This problem has been solved!
Unlock 1 Answer and 8 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE