Replacing newline in multiline textbox with <br/> - c#

I am trying to use a multiline textbox to insert text into a table which is displayed as html. I want to with javascript take the text inside of the textbox and find where the user pressed enter and place "<br/>" in that position so when the text is displayed it will show line break. Any ideas on how I could do this?
I tried something like this but it did not work.
var text = document.getElementById("announcementid").value;
var newtext = text.replace("\n", "<br/>");
text = newtext;

The newtext variable ends up being a copy of the original string from your announcementid element. Thus, you'll need to re-set the value property on the original document element:
var text = document.getElementById("announcementid").value;
var newtext = text.replace(/\n/g, "<br />");
document.getElementById("announcementid").value = newtext;
Also, as Konstantin pointed out, the replace() function in Javascript will just replace the first instance unless you pass in a global regular expression.
Fiddle example

Text is a primitive so it would not replace the value. Use a regular expression to globally replace instead of replacing just the first instance:
var text = document.getElementById("announcementid").value;
var newtext = text.replace(/\n/g, "<br />");
document.getElementById("announcementid").value = newtext;

Related

how to remove a string in a line of Multiline textbox c#

i have the data bellow in my multiline textbox in my form
what i want is remove the " -" from that line, i wanna just to remove in that first line but without changing the rest of textbox values
what i have tried but without sucess
Textbox1.Lines[0] = Textbox1.Lines[0].Replace(" -", "");
According to the documentation for the Lines property:
Note
By default, the collection of lines is a read-only copy of the lines in the TextBox. To get a writable collection of lines, use code similar to the following: textBox1.Lines = new string[] { "abcd" };
So, it seems we need to assign it a whole new array, not just modify an existing array value. Something like this should do the trick:
var newLines = Textbox1.Lines; // Capture the read-only array locally
newLines[0] = newLines[0].Replace(" -", ""); // Now we can modify a value
Textbox1.Lines = newLines; // And reassign it to our textbox

Small Bug When When Appending Text To Multiline Text Box (C#)

i have multiline text box in my form with existing text and I am trying to append text lines on new line and everything works fine but the first line always get added with the existing last line.
Example
text box holds this value
test1
and I am using below code to enter new line
txtMasterResults.AppendText(String.Join(Environment.NewLine, "line 2"));
txtMasterResults.AppendText(String.Join(Environment.NewLine, "line 3"));
and results looks like this
test1line2
line3
how can I fix the first line of textbox so I get the new text from secondline ?
I would retrieve the old string, remove any newlines at the end, and then append the new content. So like this:
txtMasterResults.Text = txtMasterResults.Text.Trim() + "\n" + newText
String.Join joins strings from an array using a delimiter. This is not what you want here.
Use:
txtMasterResults.Text += Environment.NewLine + "line 2" + Environment.NewLine + "line 3";
Note that
txtMasterResults.Text += "something"; is the same as
txtMasterResults.Text = txtMasterResults.Text + "something";

Clipboard can copy a few words?

I'm weak in English so I hope you will understand this.
I learned yesterday that Clipboard is copy.
//textBox1.Text = "My name is not exciting";
Clipboard.SetText(textBox1.Text);
textBox2.Text = Clipboard.GetText();
This code copies your everything from the textbox1 and paste it in textbox2 right?
So it's possible to copy only a few words from textbox1 and paste it in textbox2?
If you don't understand, I'm want copy only a few words not all the line.
Even if this high level code still bring me :)
Clipboard.GetText(); will return the raw copied elements.
What you can do is save them to some variable:
string text = Clipboard().GetText();
Then do something with text, to get the elements you need:
textBox2.Text = text.Substring(0, 10); // An example.
The main idea to take away from this is, GetText() will give you a string. It's up to you to slice and dice that string any way you see fit and then make use of the results.
You don't need the Clipboard for this. Your user won't like that ;)
Just create a variable like this:
string box1Content = textBox1.Text;
textBox2.Text = boxContent;
You can even skip that variable.
If you really want to use the clipboard, your way is doing that.
For just getting some text out of the textbox you can either use substring or regular expressions.
http://msdn.microsoft.com/en-us/library/aka44szs.aspx
Good luck
Daniel, the substring method is a good one to use. You simply tell it where you want to take a piece of your text and it will create a new string of just that.
textBox1.Text = "MY name is not exciting";
//pretend you only want "not exciting" to show
int index = textBox1.Text.IndexOf("not");//get the index of where "not" shows up so you can cut away starting on that word.
string partofText = textBox1.Text.Substring(index);//substring uses the index (in this case, index of "not") to take a piece of the text.
Clipboard.SetText(partofText);
textBox2.Text = Clipboard.GetText();
To my mind is better idea to take selected text from text box.
I'm not sure witch kind of text box you are using but so show example on WPF you should use TextBox.SelectedText property.
I like linq. :-)
This is a example for splitting the string, enumerable it and concats in one:
textBox1.Text = "My name is not exciting";
int firstWord = 2;
int lastWord = 4;
string[] wordList = textBox1.Text.Split(new[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
string newText = string.Concat(wordList.Where((word, count) => count >= firstWord - 1 && count < lastWord).Select(w => w + " ")).TrimEnd();
Clipboard.SetText(newText);
textBox2.Text = Clipboard.GetText();
// Result: "name is not"
Edit: and without Clipboard you can use simply this Line
textBox2.Text = newText;

What's the difference if you use a "+" or no "+" in outputting?

Div1.InnerHtml = (someString);
-VS-
Div1.InnerHtml += (someString);
I notice they both do the same thing, but is there any real difference whether I have the + in there or not?
Also.. What's the difference between InnerText & InnerHtml?
+= will append (someString) to the existing value of Div1.InnerHtml, whereas = will replace the value of Div1.InnerHtml with (someString).
If the results are the same then the starting value of Div1.InnerHtml is likely null or string.Empty ("")
Regarding InnerText vs InnerHtml: InnerHtml might return something like <h1>Hello World</h1> whereas InnerText would return Hello World (the value of the element without the actual HTML element).
Consider these cases:
string someString = "Hello";
string innerHtml = "";
innerHtml += someString; // result will be "Hello"
string someString = "Hello";
string innerHtml = "";
innerHtml = someString; // result will be "Hello"
string someString = "Hello";
string innerHtml = "World";
innerHtml += someString; // result will be "HelloWorld"
string someString = "Hello";
string innerHtml = "World";
innerHtml = someString; // result will be "Hello"
Answer of first question
C# String Append
-: += append string with the existing string
other example is
string s = "abc";
s+="cde";
output
s = "abcde"
Answer of second question
innerText will retrieve the value as it, though if it contains the tags, it will render the text as it is, where as innerHTML retrives the values by applying the HTML tags if any.
They are not the same thing at all. This is about strings manipulation and not something specific and related to ASP.NET
The first puts someString in the string property InnerHtml of Div1,
The second sets InnerHtml to be InnerHtml +(someString), so if, for example InnerHtml contained the string "aa" before this operation, it'll become "aaSomeString" at the later case, and "SomeString" at the former case.
They're only doing the same thing because Div1 is empty when you do +=
+= is appending so if you did that a few times in a row you would see that you're getting data you may not have expected.
The assignment operator (=) will simply set the value of Div1 to whatever's on the left regardless of what was there previously.
+= is concatenation (shortform for a = a + b)
= will overwrite the value with the new one on the righthand side
innerHtml will allow you to add tags like <p> and div
innerText will encode those tags as <p> and <div>
+= is a shorthand operator
for e.g.
i = i + (some value) and i+=(some value) both is same.
So, in general term,
Left_Val (operator)= right_val and Left_Val = Left_Val (operator) right_val are same
Please note that operator should be binary. shorthand operators cannot be used with unary (like unary minus) and ternary operator(like ?:).

How to add a line to a multiline TextBox?

How can i add a line of text to a multi-line TextBox?
e.g. pseudocode;
textBox1.Clear();
textBox1.Lines.Add("1000+");
textBox1.Lines.Add("750-999");
textBox1.Lines.Add("400-749");
...snip...
textBox1.Lines.Add("40-59");
or
textBox1.Lines.Append("brown");
textBox1.Lines.Append("brwn");
textBox1.Lines.Append("brn");
textBox1.Lines.Append("brow");
textBox1.Lines.Append("br");
textBox1.Lines.Append("brw");
textBox1.Lines.Append("brwm");
textBox1.Lines.Append("bron");
textBox1.Lines.Append("bwn");
textBox1.Lines.Append("brnw");
textBox1.Lines.Append("bren");
textBox1.Lines.Append("broe");
textBox1.Lines.Append("bewn");
The only methods that TextBox.Lines implements (that i can see) are:
Clone
CopyTo
Equals
GetType
GetHashCode
GetEnumerator
Initialize
GetLowerBound
GetUpperBound
GetLength
GetLongLength
GetValue
SetValue
ToString
#Casperah pointed out that i'm thinking about it wrong:
A TextBox doesn't have lines
it has text
that text can be split on the CRLF into lines, if requested
but there is no notion of lines
The question then is how to accomplish what i want, rather than what WinForms lets me.
There are subtle bugs in the other given variants:
textBox1.AppendText("Hello" + Environment.NewLine);
textBox1.AppendText("Hello" + "\r\n");
textBox1.Text += "Hello\r\n"
textbox1.Text += System.Environment.NewLine + "brown";
They either append or prepend a newline when one (might) not be required.
So, extension helper:
public static class WinFormsExtensions
{
public static void AppendLine(this TextBox source, string value)
{
if (source.Text.Length==0)
source.Text = value;
else
source.AppendText("\r\n"+value);
}
}
So now:
textBox1.Clear();
textBox1.AppendLine("red");
textBox1.AppendLine("green");
textBox1.AppendLine("blue");
and
textBox1.AppendLine(String.Format("Processing file {0}", filename));
Note: Any code is released into the public domain. No attribution required.
I would go with the System.Environment.NewLine or a StringBuilder
Then you could add lines with a string builder like this:
StringBuilder sb = new StringBuilder();
sb.AppendLine("brown");
sb.AppendLine("brwn");
textbox1.Text += sb.ToString();
or NewLine like this:
textbox1.Text += System.Environment.NewLine + "brown";
Better:
StringBuilder sb = new StringBuilder(textbox1.Text);
sb.AppendLine("brown");
sb.AppendLine("brwn");
textbox1.Text = sb.ToString();
Append a \r\n to the string to put the text on a new line.
textBox1.Text += ("brown\r\n");
textBox1.Text += ("brwn");
This will produce the two entries on separate lines.
Try this
textBox1.Text += "SomeText\r\n"
you can also try
textBox1.Text += "SomeText" + Environment.NewLine;
Where \r is carriage return and \n is new line
You have to use the AppendText method of the textbox directly. If you try to use the Text property, the textbox will not scroll down as new line are appended.
textBox1.AppendText("Hello" + Environment.NewLine);
The "Lines" property of a TextBox is an array of strings. By definition, you cannot add elements to an existing string[], like you can to a List<string>. There is simply no method available for the purpose. You must instead create a new string[] based on the current Lines reference, and assign it to Lines.
Using a little Linq (.NET 3.5 or later):
textBox1.Lines = textBox.Lines.Concat(new[]{"Some Text"}).ToArray();
This code is fine for adding one new line at a time based on user interaction, but for initializing a textbox with a few dozen new lines, it will perform very poorly. If you're setting the initial value of a TextBox, I would either set the Text property directly using a StringBuilder (as other answers have mentioned), or if you're set on manipulating the Lines property, use a List to compile the collection of values and then convert it to an array to assign to Lines:
var myLines = new List<string>();
myLines.Add("brown");
myLines.Add("brwn");
myLines.Add("brn");
myLines.Add("brow");
myLines.Add("br");
myLines.Add("brw");
...
textBox1.Lines = myLines.ToArray();
Even then, because the Lines array is a calculated property, this involves a lot of unnecessary conversion behind the scenes.
The adding of Environment.NewLine or \r\n was not working for me, initially, with my textbox. I found I had forgotten to go into the textbox's Behavior properties and set the "Multiline" property to "True" for it to add the lines! I just thought I'd add this caveat since no one else did in the answers, above, and I had thought the box was just going to auto-expand and forgot I needed to actually set the Mulitline property for it to work. I know it's sort of a bonehead thing (which is the kind of thing that happens to us late on a Friday afternoon), but it might help someone remember to check that. Also, in the Appearance section is the "ScrollBars" property that I needed to set to "Both", to get both horizontal and vertical bars so that text could actually be scrolled and seen in its entirety. So the answer here isn't just a code one by appending Environment.NewLine or \r\n to the .Text, but also make sure your box is set up properly with the right properties.
Just put a line break into your text.
You don't add lines as a method. Multiline just supports the use of line breaks.
If you know how many lines you want, create an array of String with that many members (e.g. myStringArray).
Then use myListBox.Lines = myStringArray;
Above methods did not work for me. I got the following exception:
Exception : 'System.InvalidOperationException' in System.Windows.Forms.dll
Turns out I needed to call Invoke on my controls first. See answer here.

Categories