Question

I'm trying to use conditional string format in order to show records found or not like this "5 of 10 rows found"

string msg = "{0:#;;} of {1:#;;} {2:rows;no rows;row} found";
return string.Format(msg, searchItems, totalItems, totalItems - 1);

Everything works very well until totalItems is 0 because then I got the message set like this. " of no rows found" (WRONG)

I would like something like this "no rows found"

searchItems = 0 ; totalItems = 0 ==> "no rows found"

searchItems = 1 ; totalItems = 1 ==> "1 row found"

searchItems = 2 ; totalItems = 5 ==> "2 of 5 rows found"
Was it helpful?

Solution

You could just add a .ToString() to the searchItems variable, e.g:

string msg = "{0:#;;} of {1:#;;} {2:rows;no rows;row} found";
return string.Format(msg, searchItems.ToString(), totalItems, totalItems - 1);

Assuming searchItems and totalItems are both 0:

0 of no rows found

Assuming searchItems and totalItems are both 1:

1 of 1 row found

Assuming searchItems is 2 and totalItems is 5:

2 of 5 rows found

However, I would rewrite this and use an if statement, which may be more lines of code, but is far more readable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top