Reputation: 85
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
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
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
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
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