TextBox MultiLine within winforms application - c#

How to insert a new line in textbox whithin winforms application :
textBox2.Text += "a";
textBox2.Text += "\n";
textBox2.Text += "b";
But the I get one row even I made the textbox multiline :
How can I fix this issue?

Use Environment.NewLine
textbox.Multiline = true;
textbox.Text += "a" + Environment.NewLine + "b";

for Windows OS you should write \r\n for new line.
for Mac OS you should use \n only.
The Environment.NewLine will work for both operating system. Thus, you can make your code common for both platform. So, avoid \n and \r\n in the string when your application code is created for both operating system.
in your case you can use String.Format to avoid multiple concatenation which will slow down the performance when it is being used in long process.
textBox2.Text = String.Format("ABCD{0}XYZ", Environment.NewLine);
if you are concatenating bunch of lines then there is better way to do this. You can use StringBuilder class for that.
StringBuilder sb = new StringBuilder();
foreach(string line in Lines)
{
sb.AppendLine(line);
//or
//sb.AppendFormat("My line: {0}{1}", line, Environment.NewLine);
}
textBox2.Text = sb.ToString();
StringBuilder.AppendLine() can be used also to add lines when you combining more than one lines.

As Brian said you need CRLF which means:
textBox2.Text += "a";
textBox2.Text += "\r\n";
textBox2.Text += "b";
But as Amir correctly said, Environment.NewLine will do the trick as well and you don't have to bother with "how a newline is represented".

Related

programmatic textblock entry with linebreaks

How do I programmatically add text with line breaks to a textblock?
If I insert text like this:
helpBlock.Text = "Here is some text. <LineBreak/> Here is <LineBreak/> some <LineBreak/> more.";
Then the linebreaks get interpreted as part of the string literal. I want it to be more like what would happen if I had it in the XAML.
I can't seem to do it the WPF way either:
helpBlock.Inlines.Add("Here is some content.");
Since the Add() method wants to accept objects of type "inline".
I can't create an Inline object and pass it as a parameter because it is "inaccessible due to its protection level:
helpBlock.Inlines.Add(new Windows.UI.Xaml.Documents.Inline("More text"));
I don't see a way to programmatically add runs.
I can find a ton of WPF examples of this, but nothing for WinRT.
I've also turned up a lot of XAML examples, but nothing from C#.
You could just pass in newline \n instead of <LineBreak/>
helpBlock.Text = "Here is some text. \n Here is \n some \n more.";
Or in Xaml you would use the Hex value of newline
<TextBlock Text="Here is some text.
Here is
some
more."/>
Both results:
Use Enviroment.NewLine
testText.Text = "Testing 123" + Environment.NewLine + "Testing ABC";
StringBuilder builder = new StringBuilder();
builder.Append(Environment.NewLine);
builder.Append("Test Text");
builder.Append(Environment.NewLine);
builder.Append("Test 2 Text");
testText.Text += builder.ToString();
You could convert \n to <LineBreak/> programmatically.
string text = "This is a line.\nThis is another line.";
IList<string> lines = text.Split(new string[] { #"\n" }, StringSplitOptions.None);
TextBlock tb = new TextBlock();
foreach (string line in lines)
{
tb.Inlines.Add(line);
tb.Inlines.Add(new LineBreak());
}
Solution:
I would use "\n" instead of linebreaks. Best way would be use it on this way:
Resources.resx file:
myTextline: "Here is some text. \n Here is \n some \n more."
In yours Class:
helpBlock.Text = Resources.myTextline;
This will looks like:
Other solution would be to build your string here with Environment.NewLine.
StringBuilder builder = new StringBuilder();
builder.Append(Environment.NewLine);
builder.Append(Resources.line1);
builder.Append(Environment.NewLine);
builder.Append(Resources.line2);
helpBlock.Text += builder.ToString();
Or use here "\n"
StringBuilder builder = new StringBuilder();
builder.Append("\n");
builder.Append(Resources.line1);
builder.Append("\n");
builder.Append(Resources.line2);
helpBlock.Text += builder.ToString();
I have one component XAML
<TextBlock x:Name="textLog" TextWrapping="Wrap" Background="#FFDEDEDE"/>
Then I pass the string + Environment.NewLine;
Example:
textLog.Inlines.Add("Inicio do processamento " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + Environment.NewLine);
textLog.Inlines.Add("-----------------------------------" + Environment.NewLine);
The result is
Inicio do processamento 19/08/2019 20:31:13
-----------------------------------

C# : Printing variables and text in a textbox

I need to know the command that I can print a sentence like "the item Peter at row 233 and column 1222 is not a number " .
I far as now I have made this:
string[] lineItems = (string[])List[]
if (!Regex.IsMatch(lineItems[0], (#"^\d*$")))
textBox2.Text += " The number ,lineItems[0], is bigger than
10 " + Environment.NewLine;
I want to print the array fields that have error. So if it finds something it will print it.
I made a code that correctly prints that there is an error on this line of the array, but I cant print the item of the array.
I need to have an Environment.NewLine because I will print many lines.
Thanks ,
George.
foreach (int lineNumber in lineItems)
{
if (lineNumber > 10)
textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";
}
Something like this should work, (I have not checked the c# code, I am working on a mac at the moment)
TextBox2.Text="This is FirstLine\nThis is Second Line";
The code is not compilable absolutely, but I may be understand what you're asking about.
If you are asking about how to compose the string of text box, by adding new strings to it, based on some desicional condition (regex), you can do folowing, pseudocode:
StringBuilder sb = new StringBuidler();
if (!Regex.IsMatch(lineItems[i], (#"^\d*$")))
sb.Append(string.Format(The number ,{0}, is bigger than 10, lineItems[i]) + Environment.NewLine);
textBox2.Text = sb.ToString();
If this is not what you want, just leave the comment, cause it's not very clear from post.
Regards.

Add spacing to textbox results

Hi there I have the following code-
richTextBox1.Text = richTextBox1.Text + action + "ok: " + ok.ToString();
richTextBox1.Text = richTextBox1.Text + "err: " + err.ToString();
richTextBox1.Text = richTextBox1.Text + "\r\n";
textBox1.Text = textBox1.Text;
The results look like -
ok:7err:0
But I want-
ok:7
err:0
With spacing, to make it look better how can I do this?
You could add another 2 lines:
richTextBox1.Text += Environment.NewLine;
richTextBox1.Text += Environment.NewLine;
between your "ok" and "err" - assuming you want a blank line between the two lines of output. However, you should either be using string.Format or a StringBuilder to create your output as concatenating strings this way in inefficient.
You also don't need the final:
textBox1.Text = textBox1.Text;
as that is just setting the text box contents back to itself and does nothing.
You've already got your answer, you just have it in the wrong place! The key is to use the escape sequence \r\n, which inserts a carriage return and a new line.
Also, there's no reason to split this code up into multiple lines. You end up incurring a performance penalty for doing so. It's better to do all of the string concatenation at one time. (You aren't doing enough concatenations here to justify using the StringBuilder class, but it's worth keeping in mind that strings are immutable in .NET and writing code accordingly.)
Try rewriting the code like this:
textBox1.Text = textBox1.Text + action + "ok: " + ok.ToString(); + "\r\n" +
"err: " + err.ToString(); + "\r\n";
You can also complete eliminate the last line of code, as that simply sets the value of textBox1.Text to itself. It's a no-op, meaning that it does nothing at all.
first that you could do all these in a single statement, second you could use += operator instead, and third what is that last statement doing?! it not needed, fourth add "\n" after each part you need there is no limit where you should put it, no "\r" needed.

How to insert newline in string literal?

In .NET I can provide both \r or \n string literals, but there is a way to insert
something like "new line" special character like Environment.NewLine static property?
Well, simple options are:
string.Format:
string x = string.Format("first line{0}second line", Environment.NewLine);
String concatenation:
string x = "first line" + Environment.NewLine + "second line";
String interpolation (in C#6 and above):
string x = $"first line{Environment.NewLine}second line";
You could also use \n everywhere, and replace:
string x = "first line\nsecond line\nthird line".Replace("\n",
Environment.NewLine);
Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.
If you want a const string that contains Environment.NewLine in it you can do something like this:
const string stringWithNewLine =
#"first line
second line
third line";
EDIT
Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:
As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n
var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();
One more way of convenient placement of Environment.NewLine in format string.
The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine
Usage
" X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
gives:
X=1
Y=2
X+Y=3
Code
///<summary>
/// Use "string".FormatIt(...) instead of string.Format("string, ...)
/// Use {nl} in text to insert Environment.NewLine
///</summary>
///<exception cref="ArgumentNullException">If format is null</exception>
[StringFormatMethod("format")]
public static string FormatIt(this string format, params object[] args)
{
if (format == null) throw new ArgumentNullException("format");
return string.Format(format.Replace("{nl}", Environment.NewLine), args);
}
Note
If you want ReSharper to highlight your parameters, add attribute to the method above
[StringFormatMethod("format")]
This implementation is obviously less efficient than just String.Format
Maybe one, who interested in this question would be interested in the next question too:
Named string formatting in C#
string myText =
#"<div class=""firstLine""></div>
<div class=""secondLine""></div>
<div class=""thirdLine""></div>";
that's not it:
string myText =
#"<div class=\"firstLine\"></div>
<div class=\"secondLine\"></div>
<div class=\"thirdLine\"></div>";
If you really want the New Line string as a constant, then you can do this:
public readonly string myVar = Environment.NewLine;
The user of the readonly keyword in C# means that this variable can only be assigned to once. You can find the documentation on it here. It allows the declaration of a constant variable whose value isn't known until execution time.
static class MyClass
{
public const string NewLine="\n";
}
string x = "first line" + MyClass.NewLine + "second line"
newer .net versions allow you to use $ in front of the literal which allows you to use variables inside like follows:
var x = $"Line 1{Environment.NewLine}Line 2{Environment.NewLine}Line 3";
If you are working with Web application you can try this.
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")
If I understand the question: Couple "\r\n" to get that new line below in a textbox. My example worked -
string s1 = comboBox1.Text; // s1 is the variable assigned to box 1, etc.
string s2 = comboBox2.Text;
string both = s1 + "\r\n" + s2;
textBox1.Text = both;
A typical answer could be s1
s2 in the text box using defined type style.
I like more the "pythonic way"
List<string> lines = new List<string> {
"line1",
"line2",
String.Format("{0} - {1} | {2}",
someVar,
othervar,
thirdVar
)
};
if(foo)
lines.Add("line3");
return String.Join(Environment.NewLine, lines);
Here, Environment.NewLine doesn't worked.
I put a "<br/>" in a string and worked.
Ex:
ltrYourLiteral.Text = "First line.<br/>Second Line.";

Why do I only see the last value from a List in my RichTextBox?

Why is this code only outputting one element from the list?
private void button3_Click(object sender, EventArgs e)
{
Tasks dosomething = new dosomething();
dosomething.calculate();
foreach(float num in dosomething.Display())
{
richTextBox1.Text = num.ToString();
}
}
Where dosomething.Display() is returning a List<float> list; with 10 floats.
You need to use
richTextBox1.Text += num.ToString();
By what you are doing, only the very last item will be displayed.
A better way would be to make use of a StringBuilder
StringBuilder sb = new StringBuilder();
foreach (float num in dosomething.Display())
{
sb.Append(num.ToString() + Environment.NewLine);
}
richTextBox1.Text = sb.ToString();
Each time the running code enters the foreach loop,
richTextBox1.Text = num.ToString();
clears the richTextBox1 and inserts num.ToString() into it. Next time the code in that foreach loop is executed, the contents are once again replaced.
I think that you are trying to append results here. There are many ways you could do this. For example, you could easily refactor that previous statement to:
richTextBox1.Text += num.ToString();
Note the += operator: += means append to. Thus, richTextBox1.Text = richTextBox1.Text + num.ToString();
Of course, you could also add whitespace to make it look pretty...
richTextBox1.Text += num.ToString()+" ";
Or, as astander suggested, you could use a StringBuilder. A StringBuilder is a very efficient class for manipulating strings without the ordinary memory penalties that doing this with regular string classes involves. In addition, the following code below (which is very similar to astander's code, as they essentially function the same way) only updates the richTextBox1 on the user interface once, rather than once for each element of the list.
StringBuilder code:
StringBuilder sbuilder = new StringBuilder(); //default StringBuilder() constructor
foreach (float num in dosomething.Display())
{
sb.Append(num.ToString() + " ");
}
//Foreach loop has ended - this means all elements of the list have been iterated through
//Now we set the contents of richTextBox1:
richTextBox1.Text = sb.ToString();
Note that in the foreach loop, we are appending to the StringBuilder, via the StringBuilder.Append() method.
Then, of course, you could, once again, change what appears between outputted floats. I just put a space in (" ").
So, to answer your question, only one appears because you are setting the value each time, rather than appending. When you set a value, the previous value is discarded.
Hope I helped!
P.S. Just saw a curious little thing in your code:
Tasks dosomething = new dosomething();
Are you sure that it wouldn't be:
Tasks dosomething = new Tasks();
But that's not related to your question.

Categories