Nikola Obretenov
Nikola Obretenov

Reputation: 85

Going on last rline in textbox

How can i get the last line in a textbox by clicking a button. With that code i get the first line ...

 private void btnProbe_Click(object sender, EventArgs e)
    {

       string[] first = txtRec.Text.Split(new char[] { '\n' }[0]);
       probe.Text = txtRec.Lines[0];
    }

Upvotes: 0

Views: 69

Answers (4)

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

You don't need to split the string, just use:

private void btnProbe_Click(object sender, EventArgs e)
{
     if(txtRec.Lines.Length>1)        
        probe.Text = txtRec.Lines[txtRec.Lines.Length - 1];
}

Upvotes: 4

code4life
code4life

Reputation: 15794

Using LINQ, the code becomes much more elegant:

var lastLineString = txtRec.Lines.Last();

** Remember to add System.Linq to your usages.

Upvotes: 2

looper
looper

Reputation: 1979

You're fine with just taking the count of the lines:

txtRec.Lines[txtRec.Lines.Length - 1];

txtRec.Lines.Length gives you the count of lines; because array-counting starts with 0, you need to substract 1

Plus, you don't need your line starting with "first".

Upvotes: 1

Nicolas Repiquet
Nicolas Repiquet

Reputation: 9265

Your first line is useless and creepy.

 private void btnProbe_Click(object sender, EventArgs e)
 {
   probe.Text = txtRec.Lines[txtRec.Lines.Length - 1];
 }

Upvotes: 0

Related Questions