I have textbox1 field in asp.net and a text area to show count of records.
I want to count the records split by , in textbox1 but when textbox1 is empty text area is showing 1.
Here is the code.
int contacts = textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
String.Split always returns at least one string, if you pass string.Empty you will get one string which is the input string(so in this case string.Empty).
Documentation:
....
If this instance does not contain any of the characters in separator,
the returned array consists of a single element that contains this instance.
You have to check it, f.e. with string.IsNullOrEmpty(or String.IsNullOrWhiteSpace):
int contacts = 0;
if(!string.IsNullOrEmpty(textbox1.Text))
contacts = textbox1.Text.Split(',').Length;
Try this
int contacts = string.IsNullOrEmpty(string.textbox1.Text)? string.empty: textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
This is because even when textbox1.Text is an empty string, that's still treated as one item. You need to use StringSplitOptions.RemoveEmptyEntries so that empty entries are ignored when producing the result of calling Split:
var contacts = textbox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Count();
To decompose what you've written into individual statements, what you have is:
var items = textbox1.Text.Split(new char[] { ', ' }, StringSplitOptions.RemoveEmptyEntries);
var countOfItems = itemsFromText.Count();
If you look at items you'll see that it's an array of strings (string[]) which contains one entry for each item in the text from textbox1.Text.
Even if an empty string is passed in (i.e. textbox1 is empty) there's still one string to be returned, hence the fact that your code as written is returning 1, whereas in countOfItems where I've broken the code apart it will have 0 because of the use of StringSplitOptions.RemoveEmptyEntries.
The documentation on msdn of the String.Split overload that takes StringSplitOptions as a parameter has more examples and detail about this.
Related
// I have a custom metadata object named boatNames__mdt and I'm using two methods to get a list of picklist values in a String[];
First Method
Map<String, boatNames__mdt> mapEd = boatNames__mdt.getAll();
string boatTypes = (string) mapEd.values()[0].BoatPick__c;
// BoatPick__c is a textarea field (Eg: 'Yacht, Sailboat')
string[] btWRAP = new string[]{};
**btWRAP**.addAll(boatTypes.normalizeSpace().split(','));
Second Method
string[] strL = new string[]{};
Schema.DescribeFieldResult dfr = Schema.SObjectType.boatNames__mdt.fields.BoatTypesPicklist__c;
// BoatTypesPicklist__c is a picklist field (Picklist Values: 'Yacht, Sailboat')
PicklistEntry[] picklistValues = dfr.getPicklistValues();
for (PicklistEntry pick : picklistValues){
**strl**.add((string) pick.getLabel());
}
Map with SOQL query
Map<Id, BoatType__c> boatMap = new Map<Id, BoatType__c>
([Select Id, Name from BoatType__c Where Name in :btWRAP]);
When I run the above Map with SOQL query(btWRAP[]) no records show up.
But when I used it using the strl[] records do show up.
I'm stunned!
Can you please explain why two identical String[] when used in exact SOQL queries behave so different?
You are comparing different things so you get different results. Multiple fails here.
mapEd.values()[0].BoatPick__c - this takes 1st element. At random. Are you sure you have only 1 element in there? You might be getting random results, good luck debugging.
normalizeSpace() and trim() - you trim the string but after splitting you don't trim the components. You don't have Sailboat, you have {space}Sailboat
String s = 'Yacht, Sailboat';
List<String> tokens = s.normalizeSpace().split(',');
System.debug(tokens.size()); // "2"
System.debug(tokens); // "(Yacht, Sailboat)", note the extra space
System.debug(tokens[1].charAt(0)); // "32", space's ASCII number
Try splitting by "comma, optionally followed by space/tab/newline/any other whitespace symbol": s.split(',\\s*'); or call normalize in a loop over the split's results?
pick.getLabel() - in code never compare using picklist labels unless you really know what you're doing. Somebody will translate the org to German, French etc and your code will break. Compare to getValue()
This is my string "search=;pageid=62,67;categoryid=0;orderby=;showon=1" I want to get 62 and 67 separately, how can I do this?
The best way is to use RegEx. You can use this expression to get the optimized result:
(\d{2})
This RegEx finds all the numbers with 2 digits only.
You can use String.Split and a Lookup<TKey, TValue>:
var yourString = " search=;pageid=62,67;categoryid=0;orderby=;showon=1";
var lookup = yourString.Trim().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(t => t.Split('='))
.ToLookup(arr => arr[0], arr => arr[1].Split(','));
string[] allPageIDs = lookup["pageid"].FirstOrDefault();
// allPageIDs can be null if the string didn't contain pageid
foreach (string id in allPageIDs)
Console.WriteLine(id);
A lookup is similar to a dictionary but it if the input sequence contains the key multiple times no exception is raised but the value contains all results. Therefore FirstOrDefault above returns the first result which is a string[] with two values 62,67 in this case.
what is wrong with this code?
bool claimExists;
string currentClaimControlNo = "700209308399870";
List<string> claimControlNo = new List<string>();
claimControlNo.Add("700209308399870");
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 14)))
claimExists = true;
else
claimExists = false;
Why the claimControlNo above is coming into false?
Since I know the value exists, how can i tune the code?
It's reporting false because you aren't asking whether the list contains the currentClaimControlNo, you're asking whether it contains a string that is the first fourteen characters of the fifteen-character string currentClaimControlNo.
Try this instead:
claimExists = claimControlNo.Any(ccn => ccn.StartsWith(currentClaimControlNo.Substring(0,14)));
Your count is wrong. There are 15 characters. Your substring is cutting off the last 0 which fails the condition.
Because you're shaving off the last digit in your substring.
if you change the line
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 14)))
to
if (claimControlNo.Contains(currentClaimControlNo.Substring(0, 15)))
it works.
Because contains on a list looks for the whole item, not a substring:
currentClaimControlNo.Substring(0, 14)
"70020930839987"
Is not the same as
700209308399870
You're missing a digit, hence why your list search is failing.
I think you are trying to find something in the list that contains that substring. Don't use the lists contain method. If you are trying to find something in the list that has the subset do this
claimExists = claimControlNo.Any(item => item.Contains(currentClaimControlNo.Substring(0, 14)))
This goes through each item in claimControlNo and each item can then check if it contains the substring.
Why do it this way? The Contains method on a string
Returns a value indicating whether the specified System.String object occurs within this string.
Which is what you want.
Contains on a list, however
Determines whether an element is in the System.Collections.Generic.List.
They aren't the same, hence your confusion
Do you really need this explaining?
You are calling Substring for 14 characters when the string is of length 15. Then you are checking if your list (which only has one item of length 15) contains an item of length 14. It doesn;t event need to check the value, the length is enough to determine it is not a match.
The solution of course is to not do the Substring, it makes not sense.
Which would look like this:
if (claimControlNo.Contains(currentClaimControlNo))
claimExists = true;
else
claimExists = false;
Then again, perhaps you know you are trimming the search, and are in fact looking for anything that has a partial match within the list?
If this is the case, then you can simply loop the list and do a Contains on each item. Something like this:
bool claimExists = false;
string searchString = currentClaimControlNo.Substring(0, 14);
foreach(var s in claimControlNo)
{
if(s.Contains(searchString))
{
claimExists = true;
break;
}
}
Or use some slightly complex (certainly more complex then I can remember off the top of my head) LINQ query. Quick guess (it's probably right to be fair, I am pretty freaking awesome):
bool claimExists = claimControlNo.Any(x => x.Contains(searchString));
Check it:
// str will be equal to 70020930839987
var str = currentClaimControlNo.Substring(0, 14);
List<string> claimControlNo = new List<string>();
claimControlNo.Add("700209308399870");
The value str isn't contained in the list.
I have an asp.net 4 textbox control that has it's text being dynamically populated by some java script. A Google Maps call to be exact. It's giving me mileage from 1 point to another. When the text displays, it shows " 234 mi" I need to get rid of the "mi" part of this text because the text is being converted to an Int32 Updating a table in my DB.
Basically I can only have an INT. Nothing else in the text box. How do I get rid of the "mi" at the end of the text?
Thanks
C#
EB
On the postback, before you save it you could:
var saveValue = Int32.Parse(tbTarget.Text.Replace("mi", string.Empty).Trim());
If your working with a variable length of chars (say someone enters miles instead) then your must do a foreach against the string (an array of char) and check isnumeric on each char.
A simple String.Substring works also:
String leftPart = TxtMileAge.Text.Substring(0, txt.IndexOf(' '));
int mileAge = int.Parse(leftPart);
This retrieves the part of the String in the range of 0 - indexOfWhiteSpace and converts it to an int
Edit: Since the value can have decimal places (as you've commented), you need to parse it to double, round it and then cast it to int:
var txtEstDistance = new TextBox() { Text = "40.2 mi" };
String leftPart = txtEstDistance.Text.Substring(0, txtEstDistance.Text.IndexOf(' '));
double distanceMiles = double.Parse(leftPart, System.Globalization.CultureInfo.InvariantCulture);
int oDdstanceMiles = (int)Math.Round(distanceMiles, MidpointRounding.AwayFromZero);
I need to get the value of the item clicked and the name of the columns.
for each(item in colunas) {
var itemok:String = item.dataField;
Alert.show(''+datagridlist.selectedItem.itemok); // show value of column
}
But this way it returns 'undefined'.
But if I put the name already in function, I can get the correct data, example:
Alert.show(''+datagridlist.selectedItem.create); // create is a column name in mysql
But this variable must be created dynamically, example:
var itemok:String = item.dataField;
Alert.show(''+datagridlist.selectedItem.itemok); // show value of column
Could someone help me? I'm at it on time and I can not convert the string to column name.
I thank you all now
for each(item in colunas)
{
var itemok:String = item.dataField;
Alert.show(''+datagridlist.selectedItem[itemok]);
}
The dot syntax to access properties/fields works only with property names. When the property name is stored in a string, use square brackets.
var t:String = "value";
//The following three lines are the same and will work
trace(something.value);
trace(something["value"]);
trace(something[t]);
//but this one won't
trace(something.t);