Kishore Kumar
Kishore Kumar

Reputation: 21863

How to design a TextBox which shows line number int he Left or Right Side?

Is there any control available which shows line number in Textbox either in the left side or right side? If not how to approach to create a control like that?

enter image description here

Upvotes: 5

Views: 5395

Answers (2)

user2284063
user2284063

Reputation: 321

For wpf I have done this by adding the following to the xaml:-

    <Grid Margin="10">
        <TextBox x:Name="TextBoxLineNumbers" FontFamily="Courier New" FontSize="18" IsReadOnly="True" TextAlignment="Right" Text="" Foreground="#50000000" Background="Transparent" Margin="0" Padding="0" HorizontalAlignment="Left" Width="60" BorderThickness="1,1,0,1"/>
        <TextBox VerticalScrollBarVisibility="Visible" AcceptsReturn="True" ScrollViewer.ScrollChanged="TextBox_ScrollChanged"  x:Name="TextBoxResult" FontFamily="Courier New" FontSize="18" TextAlignment="Left" Text="" Foreground="Black" Background="Transparent" Margin="60,0,0,0" Padding="0" BorderThickness="0,1,1,1"/>
    </Grid>

And to the xaml.cs file:-

    private void SetUpLines(string data)
    {
        int noLines = string.IsNullOrEmpty(data) ? 0 : data.Split('\n').Length;
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= noLines; i++)
        {
            sb.AppendLine(i.ToString());
        }

        TextBoxLineNumbers.Text = sb.ToString();
        TextBoxResult.Text = data??"";
    }

    private void TextBox_ScrollChanged(object sender, ScrollChangedEventArgs e)
    {
        TextBoxLineNumbers.ScrollToVerticalOffset(TextBoxResult.VerticalOffset);
    }

Call SetUpLines to populate the TextBox. Note this uses a fixed size font and doesn't do line wrapping, I did not want that. I know this is an old question but I didn't see a simple answer anywhere else.

Upvotes: 2

escargot agile
escargot agile

Reputation: 22379

Apparently you're not the first one who came across this kind of question.

So here are a few links you may find helpful:

WPF RichTextBox to create editor with line numbers

http://www.aqistar.com/

Upvotes: 3

Related Questions