views:

260

answers:

2

how can I get the lines which are have selected text in them? For example: alt text

The selected lines would be 1, 2,3 and 4 (0 being the first line)

How can I get to code like:

For Each line as string(or integer) in textbox1."SelectedLines"
  'Do something here for each line
Next

Thanks

+3  A: 

I think you're looking for the SelectedText property. (in C#)

foreach(string line in textBox1.SelectedText.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries))
{
    //dostuffhere
}

(in my attempt at VB)

   Dim splitter(1) As String
   splitter(0) = Environment.NewLine
    For Each y As String In TextBox1.SelectedText.Split(splitter, StringSplitOptions.RemoveEmptyEntries)
         //do stuff here
   Next
s_hewitt
+2  A: 

Taking you literally, you need to find the line numbers, even though only parts of line 1 and 4 are selected. Do that as follows:

    If RichTextBox1.SelectionLength > 0 Then
        Dim firstLine As Integer = RichTextBox1.GetLineFromCharIndex(RichTextBox1.SelectionStart)
        Dim lastLine As Integer = RichTextBox1.GetLineFromCharIndex(RichTextBox1.SelectionStart + RichTextBox1.SelectionLength)
        For line As Integer = firstLine To lastLine
            Dim txt = RichTextBox1.Lines(line)
            ' do something...
        Next
    End If
Hans Passant
FYI - if this is what the question was asking - these same methods are also available on the regular TextBox control.
s_hewitt
Thanks, I realised after asking I needed the line numbers, but thanks for the other answer s_hewitt
Jonathan