Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linebreak in WinForms Textbox

Tags:

c#

regex

winforms

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?

like image 531
F.P Avatar asked Feb 12 '26 23:02

F.P


1 Answers

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?)

like image 124
Lasse Espeholt Avatar answered Feb 15 '26 13:02

Lasse Espeholt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!