user3448117
user3448117

Reputation: 85

Getting text from specific richtextbox line

I am still new to using forms and every thing that comes with it i am wanting to get all of the text from the first line in a richtextbox and nothing else with it. I have been looking into this for about 3 hours now and haven't gotten any closer to figuring it out if any one could help would be great.

Upvotes: 2

Views: 7793

Answers (4)

Yaroy Díaz
Yaroy Díaz

Reputation: 21

You can get a specific line you need by checking for a containing value.

    public static string GetLine(RichTextBox richTb, string myValue)
    {
        string[] lines = richTb.Lines;
        foreach (var line in lines)
        {
            if (line.Contains(myValue))
            {
                return line;
            }
        }
        return null;
    }

Or you can get something else like a name doing this:

    public static string GetSpecificValue(RichTextBox richTb, string myValue)
    {
        string[] lines = richTb.Lines;
        foreach (var line in lines)
        {
            if (line.Contains(myValue))
            {
                return line.Split(':')[1].TrimStart();
            }
        }
        return null;
    }
      
    

In this case, this is the use of it:

    private void GetName()
    {
        /* Assuming there is a line that reads
         * Name: John Doe, then the returned value
         * would be John Doe */

        txtName.Text = GetSpecificValue(richTextBox, "Name");
    }

Upvotes: 0

Guilherme Oliveira
Guilherme Oliveira

Reputation: 2028

You could try this to get the first line:

var line = richTextBox1.Lines[0];

or using LINQ:

var line = richTextBox1.Lines.FirstOrDefault();

You can read more about RichTextBox here.

Upvotes: 0

Hank G
Hank G

Reputation: 487

This will work:

string firstLine = RichTextBox.Lines[0];

You could use the same logic to get any of the lines.

Upvotes: 5

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

Try This:

var firstLine = RichTextBox1.Text.Split(Environment.NewLine)[0];

Upvotes: 0

Related Questions