Trim And Capitalize

I discovered during some initial testing that if you attempted to save an item without entering in an item name the app would crash. So I added some error checking and text formatting (but not in that order).

void OnSaveClicked(object sender, EventArgs args)
	string itemName = TrimAndCapitalize(itemEntry.Text);

	if (NotValidItem(itemName)) return;

	// Additional code removed for clarity

The TrimAndCapitalize method removes any leading or trailing spaces and capitalizes the initial letter of each word in the item name.

private string TrimAndCapitalize(string name)
	if (String.IsNullOrWhiteSpace(name)) return String.Empty;

	name = name.Trim(); // Remove any leading and trailing spaces

	name = Char.ToUpper(name[0]) + name.Substring(1); // Capitalize first letter

	// Capitalize any other letter preceded by a space
	for (int i = 1; i < name.Length; i++) {
		if (Char.IsWhiteSpace(name[i - 1])) {
			name = name.Substring(0, i) + Char.ToUpper(name[i]) + name.Substring(i + 1);

	return name;

The NotValidItem method aborts the add if the item name field is empty or null.

private bool NotValidItem(string name)
	if (String.IsNullOrEmpty(name) || name.Length == 0) {
		DisplayAlert("Invalid Item Name", "Only valid item names can be added to the list.", "OK");
		return true;
	else return false;
This entry was posted in Side Projects, Software Development and tagged , , . Bookmark the permalink.