Trim Method Doesn't Clear All Spaces - c#

Hi i'm working on a basic windows form in c# and I have a little problem with the Trim() method.
There are 3 text boxes in witch the user enters his first name, last name and an ID.
Then he can save the info by clicking on a save button but I want to make sure that he doesn't leave blank boxes so I do the following test:
string CFN = Curator_FN.Text;
string CLN = CURATOR_LN.Text;
string CID = CURATOR_ID.Text;
Curator_FN.Text.Trim();
CURATOR_ID.Text.Trim();
CURATOR_LN.Text.Trim();
if (((Curator_FN.Text.Length == 0) || (CURATOR_ID.Text.Length == 0) || (CURATOR_LN.Text.Length == 0)))
{
MessageBox.Show("You Have to enter a First Name, a Last Name and an ID");
Empty = true;
}
The problem is if I just make some blank space with the space bar the Trim() method doesn't consider them as a blank space..
Maybe I just misunderstand the Trim() method and if I do, do you have any idea on how I could do the this?
Thanks in advance.

The Trim method does not modify the contents of the text boxes, it simply returns the trimmed version. You need to store this version, for example
Curator_FN.Text = Curator_FN.Text.Trim();
Of course this has the potential to make changes visible to the user (and it also has to access the UI thread which under other circumstances might be a problem), so it is far better to use a local variable as in
var curatorFn = Curator_FN.Text.Trim();
// etc
if (curatorFn.Length == 0 || ... ) {
// show messagebox
}
Of course if this is all you need to do, using string.IsNullOrWhiteSpace might be a more convenient alternative.

Since strings are immutable in C#, the Trim() method doesn't change the string itself; it returns a new instance of the trimmed string.
You need to assign the results of the method calls to the variables, i.e.
CFN = Curator_FN.Text.Trim()
And then check whether or not CFN is empty.

Trim does not modify the string. You want:
Curator_FN.Text = Curator_FN.Text.Trim();
CURATOR_ID.Text = CURATOR_ID.Text.Trim();
CURATOR_LN.Text = CURATOR_LN.Text.Trim();
Also, if you're using .NET 4 you might want to check into the String.IsNullOrWhiteSpace method as well.
if (String.IsNullOrWhiteSpace(Curator_FN.Text) ||
String.IsNullOrWhiteSpace(CURATOR_ID.Text) ||
String.IsNullOrWhiteSpace(CURATOR_LN.Text)
{
//..
}

Trim does not modify the string itself. It returns a new trimmed string.
If you don't really care about modifying the variable, look at the IsNullOrWhiteSpace method.
if (String.IsNullOrWhiteSpace(curatorFn) || ... ) {
// show messagebox
}

Related

How to remove character from string?

I have a string which is getting from a userInput. What I want to do now is removing a unique character from this string but only remove it once. The main problem is that this unique character doesn't have a unique index. For example:
User has input a string like : "0123456", and now I want to remove the first '1',so the string will be output like "023456". How ever, if a user input a string like "01123456", how can I remove the first '1' and make it looks like "0123456"? I am looking for a method that can be used for both of situation. I was using string.TrimStart(), but doesn't get what I want. How can I do this?
You could use Remove and IndexOf.
var str = "01123456";
var i = str.IndexOf('1'); // IndexOf returns -1 when there is no element found, so we need to handle that when calling remove.
var res = (i >= 0) ? str.Remove(i, 1) : str;
Console.WriteLine(res); // 0123456
I think you what you need is string.Remove method. See MSDN documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=netframework-4.7.2#System_String_Remove_System_Int32_System_Int32_
If you don't know where is your character, at first call string.IndexOf to find it. If this call returns nonnegaive number, call Remove to remove it. Just note that string is immutable so it will always create a new object.
yourstring = yourstring.IndexOf('1') != -1 ? yourstring.Remove(yourstring.IndexOf('1'), 1) : yourstring;
Another way would be to use a combination of Contains, Remove, and IndexOf:
if (userInput.Contains('1')) userInput = userInput.Remove(userInput.IndexOf('1'), 1);
Or if you want to be Linq-y...
userInput = string.Concat(userInput.TakeWhile(chr => chr != '1')
.Concat(userInput.SkipWhile(chr => chr != '1').Skip(1)));

Split string with plus sign as a delimiter

I have an issue with a string containing the plus sign (+).
I want to split that string (or if there is some other way to solve my problem)
string ColumnPlusLevel = "+-J10+-J10+-J10+-J10+-J10";
string strpluslevel = "";
strpluslevel = ColumnPlusLevel;
string[] strpluslevel_lines = Regex.Split(strpluslevel, "+");
foreach (string line in strpluslevel_lines)
{
MessageBox.Show(line);
strpluslevel_summa = strpluslevel_summa + line;
}
MessageBox.Show(strpluslevel_summa, "summa sumarum");
The MessageBox is for my testing purpose.
Now... The ColumnPlusLevel string can have very varied entry but it is always a repeated pattern starting with the plus sign.
i.e. "+MJ+MJ+MJ" or "+PPL14.1+PPL14.1+PPL14.1" as examples.
(It comes form Another software and I cant edit the output from that software)
How can I find out what that pattern is that is being repeated?
That in this exampels is the +-J10 or +MJ or +PPL14.1
In my case above I have tested it by using only a MessageBox to show the result but I want the repeated pattering stored in a string later on.
Maybe im doing it wrong by using Split, maybe there is another solution.
Maybe I use Split in the wrong way.
Hope you understand my problem and the result I want.
Thanks for any advice.
/Tomas
How can I find out what that pattern is that is being repeated?
Maybe i didn't understand the requirement fully, but isn't it easy as:
string[] tokens = ColumnPlusLevel.Split(new[]{'+'}, StringSplitOptions.RemoveEmptyEntries);
string first = tokens[0];
bool repeatingPattern = tokens.Skip(1).All(s => s == first);
If repeatingPattern is true you know that the pattern itself is first.
Can you maybe explain how the logic works
The line which contains tokens.Skip(1) is a LINQ query, so you need to add using System.Linq at the top of your code file. Since tokens is a string[] which implements IEnumerable<string> you can use any LINQ (extension-)method. Enumerable.Skip(1) will skip the first because i have already stored that in a variable and i want to know if all others are same. Therefore i use All which returns false as soon as one item doesn't match the condition(so one string is different to the first). If all are same you know that there is a repeating pattern which is already stored in the variable first.
You should use String.Split function :
string pattern = ColumnPlusLevel.Split("+")[0];
...but it is always a repeated pattern starting with the plus sign.
Why do you even need String.Split() here if the pattern always only repeats itself?
string input = #"+MJ+MJ+MJ";
int indexOfSecondPlus = input.IndexOf('+', 1);
string pattern = input.Remove(indexOfSecondPlus, input.Length - indexOfSecondPlus);
//pattern is now "+MJ"
No need of string split, no need to use LinQ
String has a method called Split which let's you split/divide the string based on a given character/character-set:
string givenString = "+-J10+-J10+-J10+-J10+-J10"'
string SplittedString = givenString.Split("+")[0] ///Here + is the character based on which the string would be splitted and 0 is the index number
string result = SplittedString.Replace("-","") //The mothod REPLACE replaces the given string with a targeted string,i added this so that you can get the numbers only from the string

Correct use of logical operator in C#

I have the following If block that runs upon pressing a command button on a form object. This should simply check to see if any of the four mentioned text boxes are empty and if so, display a message box then exit that procedure so that the user can correct the fields and continue.
Here is the relevant code:
if (string.IsNullOrWhiteSpace(txtName.ToString()) ||
string.IsNullOrWhiteSpace(txtID.ToString()) ||
string.IsNullOrWhiteSpace(txtSalary.ToString()) ||
string.IsNullOrWhiteSpace(txtERR.ToString()))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
I've left all the text fields blank, and even tried putting white space characters in but the conditional code isn't being executed. As the code isn't executing I'm assuming there is something wrong with my if statement, perhaps I'm not using the 'or' operator || correctly? Any help appreciated.
If you are checking textboxes you need to get the text from the textbox.
if (string.IsNullOrWhiteSpace(txtName.Text) || ...
As a little bonus you could also write it like this:
if(new [] {txtName, txtID, txtSalary, txtERR}
.Any(tb => string.IsNullOrWhiteSpace(tb.Text)))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
You should use Text property of TextBox. ToString method returns string "System.Windows.Forms.TextBoxBase". This string is obviously never empty or null.
if (string.IsNullOrWhiteSpace(txtName.Text) ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
If txtName, txtID etc. name of controls then you need to refer to .Text property. Try something like snippet below:
if (string.IsNullOrWhiteSpace(txtName.Text) ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
TextBox.ToString() will return the type of the TextBox - thus this will never be NullOrWhiteSpace. What you want is to check the contents of the Text property like so:
if (string.IsNullOrWhiteSpace(txtName.Text ||
string.IsNullOrWhiteSpace(txtID.Text) ||
string.IsNullOrWhiteSpace(txtSalary.Text) ||
string.IsNullOrWhiteSpace(txtERR.Text))
{
MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
return;
}
I don't use IsNullOrWhiteSpace for that kind of test, instead i prefer to use IsNullOrEmpty
try this:
if (string.IsNullOrEmpty(txtName.Text)||...)
{...
or maybe txtName is returning the TEXT object...try this then
if (string.IsNullOrEmpty(txtName.Text.toString())||...)
{...

Replace string value with '0' when string is empty

I'm taking a value from a textbox and converting it to decimal. But, the textbox value could be empty. So, how could I handle empty strings from the textbox?
Unfortunately I have around 50 textboxes to deal with, so answers like 'check for null with IF condition' won't help me. My code will look ugly if I use all those IF conditions.
I have this
Convert.ToDecimal(txtSample.Text)
To handle nulls, I did this
Convert.ToDecimal(txtSample.Text = string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
But, the above code is displaying '0' in the textbox. User does not want to see '0'. Another solution is to take text box value into a variable and convert the variable like below.
string variable = txtSample.Text;
Convert.ToDecimal(variable = string.IsNullOrEmpty(variable) ? "0" : variable)
But again, I do not want to define around 50 variables. I am looking for some piece of code that handles null values during conversion without adding the extra line of code.
But, the above code is displaying '0' in the textbox. User does not want to see '0'.
This is because your statement is assigning the new value to txtSample.Text (when you do txtSample.Text = ...). Just remove the assignment:
Convert.ToDecimal(string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
To make things easier if you have many text fields to handle, you can define an extension method :
public static string ZeroIfEmpty(this string s)
{
return string.IsNullOrEmpty(s) ? "0" : s;
}
And use it like this:
Convert.ToDecimal(txtSample.Text.ZeroIfEmpty())
You could make a function to keep from copying the code all over the place.
decimal GetTextboxValue(string textboxText)
{
return Convert.ToDecimal(string.IsNullOrEmpty(textboxText) ? "0" : textboxText);
}
and then use it like this:
GetTextboxValue(txtSample.Text);
You can create an extension method for the string as below
public static decimal ToDecimal(this string strValue)
{
decimal d;
if (decimal.TryParse(strValue, out d))
return d;
return 0;
}
Then you can just txtSample.Text.ToDecimal() in every place.

Querystring - Add values to querystring in c#

How can I add values to querystring?
I'm trying to do this:
String currurl = HttpContext.Current.Request.RawUrl;
var querystring = HttpContext.Current.Request.QueryString.ToString();
var PrintURL = currurl + (String.IsNullOrEmpty(querystring)) ?
HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty;
But I keep getting this error:
Cannot implicitly convert type 'string' to 'bool'
all i'm trying to do is get current url and add ?pring=y to querystring
Well, the first problem can be solved using this instead:
var PrintURL = currurl + (String.IsNullOrEmpty(querystring) ?
HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty);
All that's changed from your original code is simply moving the closing paren from (String.IsNullOrEmpty(querystring)) (where it was unnecessary) to the end of the ?: clause. This makes it explicitly clear what you're trying to do.
Otherwise, the compiler tries to concatenate the result of String.IsNullOrEmpty(querystring) (which is a bool) to currUrl -- incorrect, and not what you intended in the first place.
However, you've got a second problem with the HttpContext.Current.Request.QueryString.Add("print", "y") statement. This returns void, not a string. You'll need to modify this part of your ternary expression so that it returns a string -- what are you trying to do?
HttpContext.Current.Request.QueryString.Add("print", "y") returns void, not a string, so you can't use that call in the ternary expression. Plus, adding to the querystring on the Request won't affect your HTTPResponse, and I'm assuming that's what you want to do. You need to craft the new URL and use response.redirect to have the browser load the new url with the updated querystring.
i figured it out.
String currurl = HttpContext.Current.Request.Url.ToString();
String querystring = null;
// Check to make sure some query string variables
// exist and if not add some and redirect.
int iqs = currurl.IndexOf('?');
if (iqs == -1)
{
String redirecturl = currurl + "?print=y";
}
not sure if this is the cleanest way but it works.
thanks all for help
There's a couple things wrong here with what you're trying to do.
The first thing is that the QueryString collection is a NameValueCollection. The Add method has a void return. So even trying to assign the result of QueryString.Add isn't going to work.
Second, you can't modify the QueryString collection. It's read-only. There's a response over on Velocity Reviews that talks to exactly what you're trying to do. Instead of trying to modify the query string, you should redirect the user with the new value.
currurl + (String.IsNullOrEmpty(querystring)
has to return a boolean so condition has to be different.
First problem is you need brackets around your statement that is using the ?:
var PrintURL = currurl + ((String.IsNullOrEmpty(querystring)) ? HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty);
The next problem is that HttpContext.Current.Request.QueryString.Add does not return anything so one side of the : returns void where the other returns and empty string.

Categories