AppendLine is not inserting new line? - c#

I have the following:
StringBuilder errors = new StringBuilder();
if(IsNullOrEmpty(value))
{
errors.AppendLine("Enter value");
}
if(IsNullOrEmpty(value2))
{
errors.AppendLine("Enter value 2");
}
I would expect this to display:
Enter value
Enter value 2
But it is displaying:
Enter value Enter value 2
I have also tried: AppendFormat("Enter value{0}",Environment.NewLine);
as well as with the \n character.
The errors string is outputted to an asp:Label like:
lblErrors.Text = errors.ToString();

As mentioned in some of the comments, HTML does not respect the new line character \n. You need to use <br/> instead.

If you'd like to preserve all formatting (including tabs, consecutive white-space, etc), you can apply the white-space:pre style to your label or use an html pre element.
Sample fiddle

I would try to do something like
if(value.Empty == null){
errors.AppendLine("Enter Value");
}
By the code you are showing it seems like it doesn't go into the if statement.

in to string u can make as well errors.Append(Enviroment.NewLine);
#Brian in c# new line isn't "\n" "\r\n" is correct syntax of new line character:)

Related

Remove html markup from string

I am reading in a field from the database and displaying in a GridView and in that field it contains <br/> tags in the text. So I am trying to remove these from the code but when I check the value of e.Row.Cells[index].Text it doesn't contain <br/> and is has ;br/> instead.
So I tried creating a function that removes any substring starting with < and ending with > or starting with & and ending with ;. The code removes the <> but it is still showing br/
Code:
index = gv.Columns.HeaderIndex("Message");
if (index > 0)
{
string message = RemoveHTMLMarkup(e.Row.Cells[index].Text);
e.Row.Cells[index].Text = message;
}
static string RemoveHTMLMarkup(string text)
{
return Regex.Replace(Regex.Replace(text, "<.+?>", string.Empty), "&.+?;", string.Empty);
}
How do I remove the <br/> tag?
Since this is a literal string, you (sh|c)ould only use String.Replace():
static string RemoveHTMLNewLines(string text)
{
return text.Replace("<br/>", string.Empty);
}
Or replace with Environment.NewLine if needed.
De-entitize the string.
Then use regex to to find and remove expected tags.
Or
If you have enough time to study and Use, then use HtmlAgilityPack package.
About HtmlAgilityPack
Nuget Package Link
Being regardless of the question, I am curious about what this is:

Find and replace file lines

I have a text file with over 12,000 lines. In that file I need to replace certain lines.
Some lines begin with a ;, some have random words, some start with space. However, I am only concerned with the two types of lines I describe below.
I have a line like
SET avariable:0 ;Comments
and I need to replace it to look like
set aDIFFvariable:0 :Integer // comments
The only CASE that is necessary is in the word Integer I needs to be capitalized.
I also have
String aSTRING(7) ;Comment
that needs to look like
STRING aSTRING(7) :array [0..7] of AnsiChar; // Comments
I need to keep all the spacing the same.
Here is what I have so far
static void Main(string[] args)
{
string text = File.ReadAllText("C:\\old.txt");
text = text.Replace("old text", "new text");
File.WriteAllText("C:\\new.txt", text);
}
I think I need to use REGEX, which I have tried to make for my first example:
\s\s[set]\s*{4}.*[:0]\s*[;].* <-- I now know this is invalid - please advise
I need help with properly setting up my program to find and replace those lines. Should I read one line at a time and if it matches then do something? I am confused really as to where to start.
BRIEF pseudo code of what I want to do
//open file
//step through file
//if line == [regex] then add/replace as needed
//else, go to next line
//if EOF, close file
Taking a stab at this separately because each line is so radically different that capturing both in the same expression will be a nightmare.
To match your first example and replace it:
String input = "SET avariable:0 ;Comments";
if (Regex.IsMatch(input, #"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?"))
{
input = Regex.Replace(input, #"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?", "$1 $2:$3 :Integer // $4";
}
Give that a shot (Play with it here: http://regex101.com/r/zY7hV2)
To match your second example and replace it:
String input = "String aSTRING(7) ;Comments";
if (Regex.IsMatch(input, #"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)"))
{
input = Regex.Replace(input, #"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)", "$1 $2($3) :array [0..$3] of AnsiChar; // $4";
}
And play around with this one here: http://regex101.com/r/jO5wP5

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.

How to prevent entry of HTML into ASP.NET Web form text box

I have several text boxes in an ASP.NET Web Form. I want to ensure that users are not entering HTML into those text boxes. However, I'm not sure how to prevent HTML from being entered. Because of this, I decided that I want to only allow alphanumeric characters, spaces, exclamation point, sharp sign, dollar signs, percentage signs, carets, stars, and left and right parenthesis. I'm omitting the ampersand because I do not want them entering something like "<script&rt;..."
How do I do this? Am I doing it the right way?
Thank you!
Have a look here
http://msdn.microsoft.com/en-us/library/ff649310.aspx
You can put a blanket statement in the web config ValidateRequest = true will check all user input and throw an error if a user inserts something with bad characters.
If you need to allow some html tags then you will need to roll your own.
The page will, by default, prevent users from posting HTML or script in textboxes or textareas. See MSDN
I've used:
HttpUtility.HtmlEncode();
More info here.
You can use a method to clean HTML codes from entry like:
public static string ClearHTML(string Str, Nullable<int> Character)
{
string MetinTxtRegex = Regex.Replace(Str, "<(.|\n)+?>", " ");
string MetinTxtSubStr = string.Empty;
if (Character.HasValue)
{
if (MetinTxtRegex.Length > Character)
{
MetinTxtSubStr = MetinTxtRegex.Substring(0, Character.Value);
MetinTxtSubStr = MetinTxtSubStr.Substring(0, MetinTxtSubStr.LastIndexOf(" ")) + "...";
}
else
{
MetinTxtSubStr = MetinTxtRegex;
}
}
else
{
MetinTxtSubStr = MetinTxtRegex;
}
return MetinTxtSubStr;
}

How can I put text from a multi-line text box into one string?

I'm faced with a bit of an issue. The scenario is that I have a multi-line text box and I want to put all that text into one single string, without any new lines in it. This is what I have at the moment:
string[] values = tbxValueList.Text.Split('\n');
foreach (string value in values)
{
if (value != "" && value != " " && value != null && value != "|")
{
valueList += value;
}
}
The problem is that no matter what I try and what I do, there is always a new line (at least I think?) in my string, so instead of getting:
"valuevaluevalue"
I get:
"value
value
value".
I've even tried to replace with string.Replace and regex.Replace, but alas to no avail. Please advise.
Yours sincerely,
Kevin van Zanten
The new line needs to be "\r\n". Better still - use Environment.NewLine.
The code is inefficient though, you are creating numerous unnecessary strings and an unnecessary array. Simply use:
tbxValueList.Text.Replace(Environment.NewLine, String.Empty);
On another note, if you ever see yourself using the += operator on a string more than a couple of times then you should probably be using a StringBuilder. This is because strings are Immutable.
Note that new lines can be up to two characters depending on the platform.
You should replace both CR/carriage-return (ASCII 13) and LF/linefeed (ASCII 10).
I wouldn't rely on localized data as David suggests (unless that was your intention); what if you're getting the text string from a different environment, such as from a DB which came from a Windows client?
I'd use:
tbxValueList.Text.Replace((Char)13,"").Replace((Char)10,"");
That replaces all occurrences of both characters independent of order.
Try this
tbxValueList.Text.Replace(System.Environment.NewLine, "");
try this one as well
string[] values = tbxValueList.Text.Replace("\r\n", " ").Split(' ');

Categories