Nina
Nina

Reputation: 91

How can I display an array of strings in a certain way inside a TextBox?

I am doing a graduation project on Machine Translation to translate from any language into English language.

My software accepts a string in the source language (SL) and then under each source language word it displays all the meanings ordered according to their probabilities.. something looks like this

Word1      Word2     Word3
hit        bell      man
multiply             leg

The issue is that I have to display the meanings of the first word then I have to go back to the first line to display the meanings of the second word and so on... in the same TextBox!

Is there a way in c# by which I can go back to the first line and write next to existing words?

Upvotes: 0

Views: 580

Answers (1)

Ahmed Ghoneim
Ahmed Ghoneim

Reputation: 7067

You can control cursor position (and selection) by TextBox.SelectionStart and TextBox.SelectionLength properties.

Example if you want move cursor to before 3th character set SelectionStart = 2 and SelectionLength = 0.

So, as a - assuming Windows Forms Application - solution to your issue

public class TextBoxEx : TextBox
{
    public TextBoxEx()
    { }

    public void GoTo(int line, int column)
    {
        if (line < 1 || column < 1 || this.Lines.Length < line)
            return;

        this.SelectionStart = this.GetFirstCharIndexFromLine(line - 1) + column - 1;
        this.SelectionLength = 0;
    }

    public int CurrentColumn
    {
        get { return this.SelectionStart - this.GetFirstCharIndexOfCurrentLine() + 1; }
    }

    public int CurrentLine
    {
        get { return this.GetLineFromCharIndex(this.SelectionStart) + 1; }
    }
}

OR

Just add this class to your project,

public static class Extentions
{
    public static void GoTo ( this TextBox Key , int Line , int Character )
    {
        if ( Line < 1 || Character < 1 || Key . Lines . Length < Line )
            return;

        Key . SelectionStart = Key . GetFirstCharIndexFromLine ( Line - 1 ) + Character - 1;
        Key . SelectionLength = 0;
        Key . Focus ( );
    }
} 

After adding this class to your project, you can easily navigate your TextBox by

TextBox . GoTo ( 1 , 1 ); // Navigate to the 1st line and the 1st character :)

Hope this help.

Upvotes: 1

Related Questions