Reputation: 17831
I'm having some trouble dealing with linebreaks here. Basically, the user puts in some data to a textbox that is then saved directly to the database.
When I display the data in my program, I only want to display the first line of the textbox, so I tried
Regex newLine = new Regex("/[\r\n]+/");
String[] lines = newLine.Split(row[data.textColumn.ColumnName].ToString());
SomeLabel.Text = lines[0];
But it display me all lines after another, so if the user puts in
a
b
c
The label displays
abc
How can I get this to work so it only displays the first line?
Upvotes: 3
Views: 3725
Reputation: 17782
var data = row[data.textColumn.ColumnName].ToString();
And one of these (both work with unix and windows line-seperators). The first is fastest because it does not split every line when your only using the first.
int min = Math.Min(data.IndexOf("\r\n"), data.IndexOf("\n"));
string line;
if (min != -1)
line = data.Substring(0, min);
else
line = data;
or
var lines = data.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
var line = lines[0];
(See also a few extension methods I have posted here: How can I convert a string with newlines in it to separate lines?)
Upvotes: 1
Reputation: 17782
(I have added this in another answer because this answer is rather large and I think it will make this thread more clear - please leave a comment if I should make it one answer)
I have made this extension method which often have its uses:
public static IEnumerable<string> Lines(this string data)
{
using (var sr = new StringReader(data))
{
string line;
while ((line = sr.ReadLine()) != null)
yield return line;
}
}
And you can get the first line with:
var line = data.Lines().First();
This should be a lot faster than .Split
when only a subset of the lines is used.
Upvotes: 2