how to remove a certain set of characters from textbox - c#

Ok so I'm having a problem where my converter is for some reason adding the characters "%22" to the output textbox for some of the users of my program. All I need is something that i can put into a timer that detects if "%22" is detected in the textbox, and if it is detected, it will be deleted (leaving no spaces if it is the middle of a word)
if (metroTextbox2.Text.Contains("%22")
{
metroTextbox2.Text.Remove("%22");
}
(That code above doesn't work btw. It leaves an error under ("%22") on the code "metroTextbox2.Text.Remove("%22");")

Remove gets int parameter and not string.
Please use String.Replace method instead.
I.e.
metroTextbox2.Text = metroTextbox2.Text.Replace("%22", string.Empty);

Instead using REMOVE try use REPLACE Like this :
if (!metroTextbox2.Text.Contains("%22")
{
metroTextbox2.Text.Replace("%22", "");
}

Related

HttpRequestValidationException workaround

I have a textbox that when user inputs a string such as "<daily" (to signify less than daily) it throws a HttpRequestValidationException. However if there is a space between the less than symbol and the string, it works fine such as "< daily".
I have had it change the value that is submitted in the code behind by using the replace function. For example:
string s = "This is a <test";
if(s.Contains("<")){
s = s.Replace("<", "< "); //I have also used "<" & "<"
}
However, I still get the exception because in the textbox it is still showing it as "<daily". I am wondering if there is a way that if the focus is off the textbox to dynamically add a space to the string?
I understand that the HttpRequestValidationException is not supposed to allow those characters, but it seems to allow if there are spaces. Any thoughts?
It would be nice to know how you use the string in the HttpRequest. Depending on how and where you use we could come up with some ideas.

Can't clear the white spaces with the most common methods

This is the case - I need to work with the Text property of a ToolStripItem and I need to clear all white spaces from the string before that. However I tried three very common (in my opinion) scenarios and neither of them returned a string with no white spaces. Here is what I tried:
string tempBtnText = tempItem.Text;
tempBtnText is defined inside the method where I work with the Text property. I find it easier this way. Then I tried those:
tempBtnText.Replace(" ", String.Empty);
tempBtnText = Regex.Replace(tempItem.Text, #"^\s*$\n", string.Empty);
string tempBtnTexts = Regex.Replace(tempItem.Text, #"\s+", "");
All those returned the string in it's original form (with white spaces). The only way to remove the white spaces was by using this method :
public string RemoveWhitespace(string input)
{
return new string(input.ToCharArray()
.Where(c => !Char.IsWhiteSpace(c))
.ToArray());
}
Which I found in a similar post here in SO. but I really don't understand why all of the above approaches don't work. I'm starting to think that there is something to do with the fact that I'm using a ToolStripItem Text property but as shown at the very begining I declare my own string variable that takes the value of the Text property and.
I don't know. Can someone tell me, what is the reason of this behavior. Not that it's that big of a problem to use another method for clearing the white spaces but the not working options are much more compact and readable and I would like to use one of them if possible.
Strings are immutable, what means that any operation produces a new instance, so you need assign any method result back to input:
string input = "...";
intput = intput.Replace(x, y);
You are not assigning the result back to tempBtnText
tempBtnText.Replace(" ", String.Empty);
it should be:
tempBtnText = tempBtnText.Replace(" ", String.Empty);
strings are immutable, string.Replace returns a new string, it doesn't modify the existing one.
abatischev is right so writing
tempBtnText = tempBtnText.Replace(" ", String.Empty);
should solve your problems. If you only want to remove Whitespaces in front and back then rather use:
tempBtnText = tempBtnText.Trim();

Strange tag being generated in C#

I have the following GetText() function, which relates to my question, which is being called in the following place:
myGridView.DataSource = stuff.Select(s => new
{
//...some stuff here
f.Text = GetText();
}
myGridView.DataBind();
GetText looks like the following:
private void string GetText()
{
StringBuilder sb = new StringBuilder();
sb.Append("<abbr title=\"Testing\">");
sp.Append("This is the Text that I want to display");
sb.Append("<\abbr>");
}
So essentially, all I want to do is be able to have the following HTML on my webpage:
<abbr title="Testing">This is the text that I want to display</abbr>
However, there is a mysterious tag that shows up. In google chrome, I looked at th the console and I saw that it looked like this:
<abbr title="Testing">This is the text that I want to display<bbr></abbr>
There is an extraneous tag that is generated when I add in the line sb.Append("<\abbr>");
This is fixed when I remove that line, but I would like to find a better solution since this makes the code look awkward.
I also tried doing the following instead of the multi-lined sb.Appends() but the extra text is still shown.
sb.Append(string.Format("<abbr title=\"testing\">{0}<\abbr>",Text));
NOTE: Assume that Text is a string which equals the text that I want to display.
Your end tag is wrong. It should be </abbr> not <\abbr>.
<\abbr> will include an escaped a (which means nothing), inside the <bbr>. Chrome apparently closes the <abbr> tag. So the superfluous tag is actually </abbr> not <bbr>.
Use
sb.Append("</abbr>");
probably the \abbr is interpreted as an escape char \a followed by the bbr> text
By the way, looking at the escape sequences on MSDN it seems that \a is the escape sequence for the BELL character. (No, I don't think that you should hear a beep from your PC)
Here's how your method shoul like
private string GetText()
{
StringBuilder sb = new StringBuilder();
sb.Append("<abbr title=\"Testing\">");
sb.Append("This is the Text that I want to display");
sb.Append("</abbr>");
return sb.ToString();
}
"\" is an escape character :)
Just a guess but is it because you have a backslash instead of slash in your closing tag?
sb.Append("<\abbr>");
vs
sb.Append("</abbr>");
As others have said, this is the issue:
sb.Append("<\abbr>");
... but it's worth looking at exactly what's happening.
That's appending <, then a U+0007 (the "alert" character, or bell), then bbr>. If you'd done this with a character which wasn't a valid escape character (e.g. "<\zfoo>") then you'd have received a compile-time error. In some other cases you might have been able to see it in the HTML. It's only because you picked a completely invisible control character that it was harder to see.
As an aside, I don't think I've ever seen a C# program which needed \a. I wish it wasn't a valid escape character - along with the \x hex sequence...

about string removing in C#

Whats is correct to do?
check if exists, then remove?
var input = "foo #main baa";
if(input.Contains("#main")) {
input = input.Replace("#main", "");
}
or just:
input = input.Replace("#main", "");
Well, this seem a simple question,but I really want know.
Thanks in advance.
The Contains check actually just makes your code slower.
Remove it.
The Contains call needs to loop through the string until it finds #main.
The Replace call then needs to do the same exact loop (it can't remember it from the Contains call).
This is a Shlemiel the Painter's algorithm.
Replace can handle strings with zero or more occurrences of the search string, so you don't need the check.
Just do the replacement - if it's not there, nothing should happen.
Just make the call to Replace(). If the substring isn't found nothing happens and you avoid an additional call to Contains().
I would do this:
input = input.Replace("#main", "").Replace(" "," ");
To remove any double spaces.
Just remove it. The only thing to check is if the string is null or not.

.NET string IndexOf unexpected result

A string variable str contains the following somewhere inside it: se\">
I'm trying to find the beginning of it using:
str.IndexOf("se\\\">")
which returns -1
Why isn't it finding the substring?
Note: due to editing the snippet showed 5x \ for a while, the original had 3 in a row.
Your code is in fact searching for 'se\\">'. When searching for strings including backslashes I usually find it easier to use verbatim strings:
str.IndexOf(#"se\"">")
In this case you also have a quote in the search string, so there is still some escaping, but I personally find it easier to read.
Update: my answer was based on the edit that introduced extra slashes in the parameter to the IndexOf call. Based on current version, I would place my bet on str simply not containing the expected character sequence.
Update 2:
Based on the comments on this answer, it seems to be some confusion regarding the role of the '\' character in the strings. When you inspect a string in the Visual Studio debugger, it will be displayed with escaping characters.
So, if you have a text box and type 'c:\' in it, inspecting the Text property in the debugger will show 'c:\\'. An extra backslash is added for escaping purposes. The actual string content is still 'c:\' (which can be verified by checking the Length property of the string; it will be 3, not 4).
If we take the following string (taken from the comment below)
" '<em
class=\"correct_response\">a
night light</em><br
/><br /><table
width=\"100%\"><tr><td
class=\"right\">Ingrid</td></tr></table>')"
...the \" sequences are simply escaped quotation marks; the backslashes are not part of the string content. So, you are in fact looking for 'se">', not 'se\">'. Either of these will work:
str.IndexOf(#"se"">"); // verbatim string; escape quotation mark by doubling it
str.IndexOf("se\">"); // regular string; escape quotation mark using backslash
This works:
string str = "<case\\\">";
int i = str.IndexOf("se\\\">"); // i = 3
Maybe you're not correctly escaping one of the two strings?
EDIT there's an extra couple of \ in the string you are searching for.
Maybe the str variable does not actually contain the backslash.
It may be just that when you mouse over the variable while debugging, the debugger tooltip will show the escape character.
e.g. If you put a breakpoint after this assignment
string str = "123\"456";
the tooltip will show 123\"456 and not 123"456.
However if you click on the visualize icon, you will get the correct string 123"456
Following code:
public static void RunSnippet()
{
string s = File.ReadAllText (#"D:\txt.txt");
Console.WriteLine (s);
int i = s.IndexOf("se\\\">");
Console.WriteLine (i);
}
Gives following output:
some text before se\"> some text after
17
Seems like working to me...
TextBox2.Text = TextBox1.Text.IndexOf("se\"">")
seems to work in VB.
DoubleQuotes within a string need to be specified like "" Also consider using verbatim strings - So an example would be
var source = #"abdefghise\"">jklmon";
Console.WriteLine(source.IndexOf(#"se\"">")); // returns 8
If you are looking for se\">
then
str.IndexOf(#"se\"">")
is less error-prone. Note the double "" and single \
Edit, after the comment: it seems like the string may contain ecaping itself, in which case in se\"> the \" was an escaped quote, so the literal text is simply se"> and the string to use is Indexof("se\">")

Categories

Resources