Validation, Lists, and Loops

Adding validation

Validation is important when publishing anything online. You may know how that page works but your users don't! Instructions are not always read and some users want to hack your website. If a form is validated well, your feature should run as intended and your database secure.

Let's take a look at a simple application that adds two numbers.

An application that adds two numbers HTML code An application that adds two numbers C# code

Try running the application and entering words instead of numbers in the input fields. What happened?

The application works but it's not userproof. Let's add some validation to our code.

Luckily for us, C# knows that inputs in web forms are strings that need to be converted to a numberical type (int, double, float, etc.) if math is involved. It's a method called "TryParse".

                    Int.TryParse(string value, out int value)
Or, more practically using variables
                    Int.TryParse(aStringVariable, out anIntVariable)
This method evaluates if it can convert a string to an integer. If it can, it will return true and then the second parameter will take in the string variable as type int. If it can't, then it returns false. A method that returns true or false? That makes this method perfect for if/else statments.

Adding validation to our application

There are more ways to validate what we just did. For more ways, search them!

Try validating if a number is odd or even, if a number is prime, or if a number is a multiple of 5!

Lists and Foreach Loops

You may be familiar with arrays; variables that store many strings, numbers, objects, or even other arrays. C# has arrays and something similar called Lists. They behave similarly to arrays but have more features. Let's take a look at a list:

                List<string> users = new List<string> (new string[]{"Barry", "Arnold", "Cameron", "Dennis"});
A list variable first has to be decalred with the List class followed by the type its contents will be, in this case type string. You then have to decalre a new List because List is a class. When you declare a class you have you use new to let C# know that the variable you're making is a new instance of that class. After declaring a new instance of class you can either leave the parentheses empty () or write ina set of values of type string like so:

Making a list

Notice that the list is made outside of the Page_Load function. This is so that the List is accessible by not only Page_Load, but any function made afterward. If I made it inside Page_Load, the List would only be accessed in Page_Load.

Now add some user interaction in HTML. Let's allow users to find a value in our list. In this case, let users find an existing name in the list of users. To do this, we only need an input field like so:

HTML for finding a user


In the TextBox there is an attribute called OnTextChanged with the value "Find_Users". Like OnClick, this is an event listener in ASP.NET that will execute the function "Find_Users" in the code behind file associated with this HTML page. When the form submits and C# detects that the text inside that TextBox is different than the default value it was given, it will execute Find_Users. Let's make that function in the C# file:

Making the Find_Users function

Here's how the function is written:

  1. Clear the output text so what we output is clear to the user.
  2. Store the user's input in a string variable.
  3. We determine whether or not the input was found in our list of names using if/else logic. In C# you can use the Contains method on a list to return true or false. If Contains finds a matching value, it will return true, otherwise it will return false which here goes to the else clause. If a term is found, let the user know in the output. If a term isn't found, also let them know in the output.

Adding to a List

Lists can also have items added to them. Let's give the user the option to do so with an input field and a button:

The HTML for adding a user

And here is the function in the code behind:

The C# for adding a user
  1. Store the user's input in a string variable.
  2. Perform validation. The function IsNullorWhiteSpace is used to check if a value is null or just consists of white space by pressing the space bar multiple times. Don't forget to declare a type, in this case string, with this method!
  3. If the string variable we captured from the form is not null or just white space, then we can add it to our list with the method .Add(string).
  4. Let the user know their input was added to the list.
  5. Display the list with the new value but first clear the display text.
  6. Using a foreach loop, print out each value of the list. A foreach loop is different than a for loop because a foreach loop goes through each item in a list. In a for loop, you define where the loop goes and where it stops. Notice also in the foreach loop a placeholder variable must be declared. This placeholder represents the list and is used for representing that list instead of the original list being manipulated.

Removing from a List

Lists can also have items removed. Let's give the user the option to do so with an input field and a button.

HTML for removing a user

And here is the function for the code behind:

C# for removing a user
  1. Store the user's input in a string variable.
  2. Perform some validation using a method we previously used, .Contains, on our list for our user's input.
  3. If a user is found, remove it from the list by using the .Remove method on our list.
  4. Let the user know their input removed an item in the list.
  5. Clear out the display text for your incoming message to the user.
  6. Use a foreach loop to loop through each item in our list and display that item to the output.
  7. If the user wasn't found, let the user know also.

Sorting through a List

C# has a handy Sort method that rearranges a list alphabetically for strings and numerically for numbers. The HTML:

HTML for sorting a list

The C#:

C# for sorting a list
  1. Simply, use the method .Sort() on a list to rearrange its contents alphabetically.
  2. Clear the output text by replacing it with a " ".
  3. Use a foreach loop to loop through each item and display it in the output.
If you want to sort a list backward:
  1. Clear the output to avoid confusion.
  2. Set up a variable that will hold the backward list and use a statement. Like a foreach loop, these statments use a placehold value (user, in this case) instead of the actual value (users). Notice that it looks like a SQL query.
  3. Use a foreach loop to loop through the items and display it to the output.

Something isn't right, notice anything?

If you've been running the code you'll notice that the changes made to the List are only temporary. For instance, if you add a user then remove a user, you'd notice that the user you added is no longer there but you removed another user. Or if you remove a user then reload the page, the user is still there if you sort the list! That's because the OnClick and OnTextChanged events are sending form contents to the server which then processes our code behind file. To better understand this, imagine everytime you hit a button then look at the C# code from top to bottom, right to left as if the computer were reading it. This is what's happening everytime you execute an event in ASP.NET. So, everytime you're hitting "Add user", the C# file is redeclaring the users List to its original code and then adding or removing or sorting depending on the action. This is very different than Javascript, a client-side language, because in Javascript you are not communicating with the server and reloading the page. The top/down, right/left scanning of the code has been done when the page is loading so any changes to variables are there to stay until the page loads again and resets everything. Javascript does have some server capabilities, though.. To get the more permanent effect of changing data in C# and ASP.NET, we use databases and session variables instead. Databases can be thought of being very large, permanent arrays/lists with vast amounts of functionality.