locked
Textbox - How to get char position if I know line number? RRS feed

  • Question

  • I have a multiline textbox and I know the line number of a certain location.
    How can I get the character index of the first character in that line?

    Any help is highly appreciated.
    Monday, June 8, 2009 6:25 PM

Answers

  • Use the GetFirstCharIndexFromLine() method of the TextBox class.

    • Proposed as answer by Fernando Nicolet Monday, June 8, 2009 6:51 PM
    • Marked as answer by thameera Monday, June 8, 2009 7:00 PM
    Monday, June 8, 2009 6:47 PM

All replies

  • This should work for you:

    private int GetIndexCharFromLine(TextBox textBox, int lineIndex)
    {
        if (textBox == null)
        {
            throw new ArgumentNullException("textBox");
        }
        if ((lineIndex > textBox.Lines.Length) || (lineIndex <= 0))
        {
            throw new ArgumentOutOfRangeException("lineIndex");
        }
    
        return textBox.Lines
            .Take(lineIndex - 1)
            .Sum(line => line.Length + 2);
    }

    Regards,
    Fernando.
    I always try to Keep it Sharp & simple.
    Monday, June 8, 2009 6:43 PM
  • Use the GetFirstCharIndexFromLine() method of the TextBox class.

    • Proposed as answer by Fernando Nicolet Monday, June 8, 2009 6:51 PM
    • Marked as answer by thameera Monday, June 8, 2009 7:00 PM
    Monday, June 8, 2009 6:47 PM
  • string line = "some line";

    char firstChar = line[0];



    Thanks,
    A.m.a.L
    .Net Goodies
    Remember to click "mark as answered" when you get a correct reply to your question
    Monday, June 8, 2009 6:50 PM
  • Thank you very much!
    Monday, June 8, 2009 6:59 PM