The text box is empty but still shows the counter
I have a field textbox1
in asp.net and a text area to display the number of posts. I want to count the records split by textbox1
, but when textbox1
is empty text area, 1 is displayed.
Here is the code.
int contacts = textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
source to share
String.Split
always returns at least one row, if you go through string.Empty
you get one row which is the input string (so in this case string.Empty
).
.... If this instance does not contain any characters in the delimiter, the returned array consists of a single element that contains this instance .
You should check this i.e. using string.IsNullOrEmpty
(or String.IsNullOrWhiteSpace
):
int contacts = 0;
if(!string.IsNullOrEmpty(textbox1.Text))
contacts = textbox1.Text.Split(',').Length;
source to share
This is because even when textbox1.Text is an empty string, it is still treated as a single element. You need to use StringSplitOptions.RemoveEmptyEntries
to make empty entries ignored when creating the call result Split
:
var contacts = textbox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Count();
To decompose what you have written into separate statements, you have:
var items = textbox1.Text.Split(new char[] { ', ' }, StringSplitOptions.RemoveEmptyEntries);
var countOfItems = itemsFromText.Count();
If you look items
, you can see that it is an array of strings ( string[]
) that contains one entry for each item in the text from textbox1.Text
.
Even if an empty string is passed in (i.e. textbox1
empty), there is still one more string to be returned, hence the fact that your code, as written, returns 1, whereas in countOfItems
where I broke the code would be 0 from -for use StringSplitOptions.RemoveEmptyEntries
.
The msdn documentation for the String.Split overload that takes StringSplitOptions
as a parameter has more examples and details on this.
source to share