Home Page

Category: Arrays and Lists

Click here to download the sample source code for this Dictionary lab exercise 

There is another useful C# class that I would like to cover as part of the Arrays and Lists lessons.  This class is called the Dictionary.  The Dictionary is also part of the System.Collections.Generic namespace but it has a different purpose than a List object.  The Dictionary object is useful when you need to store key/value pairs in memory.  For example if you want to store attributes about a web application user such as ip address, first name, last name, userid you could setup a Dictionary as such:

Key          Value
—-          ——
ip              129.168.29.38
fname      Billy
lname      Gibbons
uid           bgibbons

You could access the last name of the user by using the syntax mydictionary[”lname”].  In a Dictionary, the key is always unique.  Let’s do an example together.  Create a new web form Default3.aspx and put a Button and a TextBox on the form.  Change the Text of the Button to “Dictionary”.  Double click the Button to create the event handler and put:

 

Dictionary<string, string> mydictionary =
    new Dictionary<string, string>();

mydictionary["ted"] = "kolovos";
mydictionary["mark"] = "jenkins";

TextBox1.Text = "The item at position ted is: " +
    mydictionary["ted"];

Make sure you have System.Collections.Generic in your namespaces at the top of the code.  In this example above, notice that inside the < > following the Dictionary type declaration I had to specify 2 things.  The first is the data type for the key of the Dictionary which is string.  The second is the data type for the value of the Dictionary which happens to also be string.  The data type for the key and value can be anything you want.

I put an item into the Dictionary using the syntax mydictionary[”ted”] and the assignment operator.  Then when I want to later determine what is stored inside the Dictionary with the key of “ted” I use the exact same syntax with the square brackets.  Remember that the key in a Dictionary is always unique.  Also note that if you are using strings as the Dictionary key, it is case sensitive, so mydictionary[”ted”] is a different place in the Dictionary versus mydictionary[”Ted”].  Because of this sometimes programmers change the key to upper case before loading data into the Dictionary and when accessing the contents to avoid invalid searches.

The Dictionary object is idea when you want to store key/value pairs or perform searches based on a key value.  If you simply want to store a list of objects and are not looking for any search capability, use the List object instead.

The Dictionary object has a method called ContainsKey which can search the Dictionary to determine if an item exists.  Here is an example that shows how it can be used:

 

Dictionary<string, string> mydictionary =
    new Dictionary<string, string>();

mydictionary["ted"] = "kolovos";
mydictionary["mark"] = "jenkins";

if (mydictionary.ContainsKey(txtFirstname.Text))
    txtOutput.Text = mydictionary[txtFirstname.Text];
else
    txtOutput.Text = "That doesn't exist";

Refer to the Default3.aspx file sample source code provided as part of Lab3_csharpuniversity.zip to see the web form for this example.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Category: Arrays and Lists

Click here to download the sample source code for this Lists lab exercise 

Now that we have seen how Arrays work, let’s take a look at a more versatile C# object: the List class.  This class is found in the System.Collections.Generic namespace.  I like to think of the List class as a fancy Array; it is very similar to an Array, with more functionality and it is more dynamic.  With a List object, you don’t have to define the size of the List ahead of time.  It can grow dynamically based on how many items you put into it.  Just that characteristic alone, makes it easier to use for a lot of C# programmers.  If you know ahead of time, how many items you need to store in a list, you may be able to use the Array, but if you are unsure, the List object may suit you better.  Let’s see an example.

Create a new web form called Default2.aspx in your Lab3 project.  Click here to watch an example video in case you forgot how to add a new web form.  Drag a Button onto the form and change the Text to “List of integers”.  Drag a TextBox onto the form and make it MultiLine.  Double click the Button to create the event handler and put the following:

 

List<int> mylist = new List<int>();

mylist.Add(33);
mylist.Add(55);
mylist.Add(10);
mylist.Add(509);

foreach (int myvar in mylist)
{
    TextBox1.Text += myvar.ToString() + "\r\n";
}

In the using statements at the top of the source code file, make sure that you have “using System.Collections.Generic” listed somewhere, otherwise you will get an error when you try to run the project and the compiler may complain it cannot find the List class.

To declare a List, I used the syntax List<int> mylist = new List<int>();  The data type is List and following the data type is an expression that tells C# what kind of type you plan to hold in the List.  In my case, my List hold int numbers so I placed that inside the < >.  Notice on the right side of the assignment operator = that I had to put parentheses after List<int>.  In the later lessons dedicated to coding and calling C# classes I talk more in detail about why this is necessary.

Putting items into the List is easy, you use the Add method mylist.Add(10);  Notice that I didn’t have to declare how big my List is, I can call the Add method as many times as I like.

To access the items in the List you can use a similar syntax to that of Arrays mylist[0] using the index number.  In the example above I used a slightly different approach which is the C# foreach loop.  The foreach loop is a special kind of loop in C# that can easily loop through Collections.  Collections are special types that facilitate this kind of iteration.  The List class is a type of Collection.

With the syntax foreach (int myvar in mylist) we can talk about each part of the foreach syntax separately.  Inside the parentheses there are 4 parts to the foreach expression.  The first part specifies the data type “int” that we are planning to read from the Collection.  The second part “myvar” is simply a temporary variable that will hold the contents of the List each time the loop iterates.  The third part is the keyword “in”.  Finally, the fourth part is the name of the Collection that you want to loop through which in this case is “mylist”, the List class.  This loop will start at the beginning of the List starting with the first item that you added into the List and end with the last item which was added to the List.  I could have also used a for loop instead of the foreach loop:

 

for (int i = 0; i < mylist.Count; i++)
{
    TextBox1.Text += mylist[i].ToString() + "\r\n";
}

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Category: Arrays and Lists

Click here to download the sample source code for this Arrays lab exercise  If you forgot how to open the files using Visual Web Developer, click here to learn How to open C# ASP.NET Website files.  Please use these files only as a reference.  You should go through the exercises yourself and create your own project according to the instructions in the exercise. 

Now that we have seen how conditionals work and practiced looping, it’s time to move on to Arrays.  Arrays are the most basic type of list object in the C# language.  An Array is basically a list of objects of any type, with a given size.  The size of the Array defines how many objects it can store.  When the Array size is declared in your C# code, the size remains fixed as you use the Array.  In other words, if you declare the Array to hold 5 integer numbers, the .NET runtime engine will allocate 5 Array placeholders in memory, ready to be populated with numbers.  You cannot put 6 numbers into that Array, it can only hold up to 5.  You can however put less than 5 if you so desire.  Keep this characteristic about Arrays in mind when you are programming.

Each item stored in an Array is held at a specific position called the index.  Arrays always start at position zero 0 and go upwards, 1, 2, 3…  Here is what an Array of numbers looks like to the C# runtime:

Index     Object
——     ——-
0             33
1             505
2             10
3             4202

Create a new website using Visual Web Developer and call the project Lab3.  Go to the Design view for the file Default.aspx.  Drag a new Button onto the form and change the Text property to say “Array of integers”.  Drag a new TextBox to the right of the Button control.  For the TextBox control, change the TextMode property to “MultiLine”.  Double click the Button to create the event handler method and put the following code for the button:

 

int[] myarray = new int[4];
myarray[0] = 33;
myarray[1] = 505;
myarray[2] = 10;
myarray[3] = 4202;

for (int i = 0; i < myarray.Length; i++)
{
    TextBox1.Text += myarray[i].ToString() + "\r\n";
}

Notice that we have declared an Array on the line int[] myarray = new int[4];  To declare an Array you have to specify what kind of data type you will stored in the array, in our case this is type int.  Then you must put the square brackets [], this tells C# that you are declaring an Array.  Following that we specify the name of our Array which is myarray.  On the right side of the equals sign we have to put the “new” keyword and then specify the size of the Array by putting a number inside the square brackets; in this case the Array can hold up to 4 integers.

To load items into the Array, we have to use the Array name “myarray” followed by square brackets and then use the index number inside the square brackets.  Then we can assign a number using the assignment operator =.  The expression myarray[0] = 33; loads the number 33 into the first position of the array.

To read items from the Array, we also use the Array name and the index number with exactly the same syntax.  If we wanted to get the number that is stored in the second position of the Array we would use the syntax myarray[1] in an expression.  Note that in the code example above I am dynamically reading the items in the Array by using the expression myarray[i].  Since the variable i increments each time the loop iterates, this is dynamically changing which position in the Array is accessed each time.  Notice that the loop starts at zero, since Arrays always start as position zero.

You can pretty much store any type of C# variable in an Array.  We have seen how to store numbers in an Array.  Let’s take a moment to experiment with an Array of strings.  Go to the Design view of the form Default.aspx.  Put your cursor to the right of the TextBox control and press Enter to create a new line.  Drag a new button onto the form and change the Text to “Array of string”.  Drag a new TextBox to the right of the button and change the TextMode to MultiLine.  Double click the button to Create the event handler.  In the event handler put the following:

 

string[] myarray = new string[3];
myarray[0] = "my first string";
myarray[1] = "my second string";
myarray[2] = "my last string";

for (int i = 0; i < myarray.Length; i++)
{
    TextBox2.Text += myarray[i] + "\r\n";
}

The syntax is almost identical to the prior example when we were working with an Array of numbers.  The only difference here is that in the for loop I didn’t have to call the ToString() method with the Array since the contents of the Array are already strings, therefore they don’t need to be converted in order to be displayed on the web page.  This is in contrast to when we were storing numbers in the array.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Click here to download the sample source code for this while loop lab exercise 

In contrast to the for loop, the “while” loop is generally useful when you are not sure how many loop iterations you will execute a block of repetitive code.  The while loop keeps executing until the termination condition statement becomes false.  Let’s see an example.

Create another Button and TextBox in your Default3.aspx web form.  Change the Button to say “while loop” and creat the event handler.  Put the following code for the Button event handler:

 

int i = 1;
while (i <= 5)
{
    TextBox2.Text += i.ToString();
    i++;
}

Notice the format of the while statement.  It is simpler than the for loop in that it only has a termination condition.  Basically this loop will keep executing as long as i is less than or equal to the value 5.  With the while loop (in contrast to the for loop), there must be something that happens inside the loop body (inside curly braces) that ensures that the loop will eventually terminate.  In our case, this is done by incrementing the i variable i++;  You must be careful not to create an infinite loop by forgetting to create some code inside the loop that ensures it will eventually terminate. 

Here is another way to write the while loop above using some extra C# code.  This will help you look at how we can use different techniques to accomplish the same thing:

 

int i = 1;
bool keeplooping = true;
while (keeplooping)
{
    TextBox3.Text += i.ToString();
    i++;
    if (i > 5)
       keeplooping = false;
}

Above I used a boolean data type as the loop variable.  This technique is easier to read and maintain for some programmers and is a matter of style.  It also gives you more options to test for different termination conditions inside the loop.  Whenever you need to terminate the loop, you simply set the keeplooping variable to false.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Click here to download the sample source code for this for loop lab exercise 

This exercise is a continuation of the Lab2 website project that we created in other lessons in the Conditionals and Loops category.  Now we are going to move on and discuss loops.  In addition to making decisions, C# offers constructs to assist with repetitive tasks and logic that is redundant through the use of loop keywords.  The first loop type commonly used is the “for” loop.

Create a new web form in the Lab2 project and leave the name as Default3.aspx.  Goto the Design view for the form and drag a Button and TextBox as we did in similar prior exercises.  Change the Text property of the Button to say “for loop” and then create the event handler method.  In the event handler put the following:

 

for (int i = 1; i <= 5; i++)
{
    TextBox1.Text += i.ToString();
}

Let’s take a look at the loop step by step.  First notice the keyword “for” which lets C# know that you want to keep repeating whatever is inside the open and closed curly braces {  } that immediately follow the “for” statement line.  The first part of the for loop is called the initialization statement, in our case this is int i = 1;  The second part of the for loop is the termination condition, in our case i <= 5;  The third part of the for loop is the increment statement, in our casee i++.

In plain English, here is how C# interprets the for loop in the example above.  First C# will execute the initialization statement before the loop runs for the first time.  So it will create a variable called i and assign a value of 1.  This happens only one time before the loop executes.

Next C# will run the termination condition to see if it is true.  If the termination condition is true, C# will keep on looping and executing all the code inside the curly braces.  If the termination condition is false, C# will no longer execute the loop.

At the end of each loop iteration (or cycle), after the code in the curly braces has been executed, C# executes the increment statement of the for loop which is i++ in our example.  In C# the ++ operator adds one to the variable that prefixes the operator.  It is the same as doing i = i + 1;  So think of it as shorthand.  Here is the order of operations in the for loop in our example:

Initialize the variable i
Is i <= 5? Yes, so execute the loop
Display the number 1 in the TextBox
Increment i by 1, i now is 2
Is i <= 5? Yes, so execute the loop
Display the number 2 in the TextBox
Increment i by 1, i now is 3
Is i <= 5? Yes, so execute the loop
Display the number 3 in the TextBox
Increment i by 1, i now is 4
Is i <= 5? Yes, so execute the loop
Display the number 4 in the TextBox
Increment i by 1, i now is 5
Is i <= 5? Yes, so execute the loop
Display the number 5 in the TextBox
Increment i by 1, i now is 6
Is i <= 5? No, so terminate the loop

A lot of C# programmers tend to start their loops with zero instead of 1 for various reasons.  I want you to see how the loop above could have been written slightly differently but still execute the same number of times:

 

for (int i = 0; i < 5; i++)
{
    TextBox1.Text += i.ToString();
}

The loop variable i (also known as the loop index variable) would have been assigned values of 0, 1, 2, 3, 4 and finally 5 at which time the loop would terminate.  This means that the loop would run a total of 5 iterations, just like in the prior example where I had started with i = 1 instead;

In my experience, for loops are generally useful if you know roughly how many times you need to execute a block of code.  For example, if you need to loop through an Array and pull items that are in that Array, the Array has a property called Length which can be used in the for loop to specify how many iterations to run.

I have also found it good practice not to change the value of the loop index variable inside of the loop body.  In other words, don’t change the value of i inside your loop.  This can create unwanted conditions that are difficult to debug and generally should be avoided.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Click here to download the sample source code for this switch statement lab exercise 

An alternative conditional statement to the “if” in C# is the “switch” statement which allows the programmer to write a more elegant “if” statement.  Its purpose is almost the same as the if, else if, else but can be easier to read and maintain in certain situations.  With the switch statement, you first have to define a variable that you will be testing for a certain condition or value.

In the Lab2 project, create a new web form.  In the Solution Explorer, right click on the project name “Lab2″ at the top and click “Add New Item”.  Make sure to click Web Form as the template, leave the name of the page as Default2.aspx, make sure the language is Visual C#, make sure the Place code in separate file is checked on, and click the Add button to create this new form.  Go to the Design view for this new page Default2.aspx.  Click here to watch an example video.

Drag a Button onto the form and change the Text property to say “switch statement with integer”.  Drag a TextBox onto the form next to the Button.  Double click on the Button to add the event handler.  In the event handler method, put the following code:


int i = 33;

switch (i)
{
    case 10:
      TextBox1.Text = "i = 10";
      break;
    case 33:
      TextBox1.Text = "i = 33";
      break;
    default:
      TextBox1.Text = "i is neither 10 nor 33";
      break;
}

At the top of the switch statement we let C# know that we are going to test the value of the variable i by using the “switch (i)” block of code.  Then the switch statement will execute each case from the top and moving downward until it finds a condition that is true.  In my example, the switch will not go into the “case 10″ because the value of the variable i is NOT 10.  It will go into the “case 33″ block because the value of i matches with 33.  The “default” is the last part of the switch statement and is there to let C# know that if none of the above conditions were true, go ahead and execute whatever is in the default portion.  This is similar to the “else” in an “if” statement in C#.  To demonstrate how the switch statement could have been written using an “if”, the following lines of code would achieve the same thing as the switch statement:

 

if (i == 10)
    TextBox1.Text = "i = 10";
else if (i == 33)
    TextBox1.Text = "i = 33";
else
    TextBox1.Text = "i is neither 33 nor 44";

To end the switch exercise, I want you to see an example of how the switch statement can be used with different variable types.  In the example below, I am using the switch with a string variable type:

 

string tedstring = "Hello ted";

switch (tedstring)
{
    case "Hello marvin":
      TextBox2.Text = "Matched with marvin";
      break;
    case "Hello lucy":
      TextBox2.Text = "Matched with lucy";
      break;
    default:
      TextBox2.Text = "Matched with ted";
      break;
}

Notice that I am using string literals to compare to the value of the variable tedstring.  Since in this example, neither of the case conditions match, the switch will fall through to the default portion.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Click here to download the sample source code for this if statement lab exercise  If you forgot how to open the files using Visual Web Developer, click here to learn How to open C# ASP.NET Website files.  Please use these files only as a reference.  You should go through the exercises yourself and create your own project according to the instructions in the exercise. 

Now that we have covered some basic data types in C#, it’s time to move on to the programming concept of conditionals and loops in .NET.  Conditional statements and operators assist the program in making decisions regarding what logic to perform.  Making decisions is one of the basic building block of all programming languages.  In C# we make decisions using the “if” statement.  The idea being “if a certain condition is true, then execute a block of code”.  Create a new website using Visual Web Developer and call the project Lab2.

Go to the Design view for the file Default.aspx.  Drag a new Button onto the form and change the Text property to say “if by itself”.  Drag a new TextBox to the right of the Button control.  Double click the Button to create the event handler method and put the following code for the button:

 

int i = 33;
int j = 33;

if (i == j)
  TextBox1.Text = "The numbers are equal";

Notice that we have declared and initialized to integer variables i and j with the same value of 33.  In the “if” statement, we are checking if they are the same by using the equality operator ==.  If the answer is yes and the numbers are the same, then the next line of code following the “if” will be executed.  Please note that it is important to use the double equals == to test for equality.

Drag a another new Button onto the form and change the Text property to say “if with an else”.  Drag a new TextBox to the right of the Button control.  Double click the Button to create the event handler method and put the following code for the button:

 

int i = 103;
int j = 55;

if (i == j)
  TextBox2.Text = "The numbers are equal";
else
  TextBox2.Text = "The numbers are not equal";

This time around, I changed the value of the variables i and j so that they are no longer the same.  Then I added an “else” part to the “if” statement so that the C# runtime engine will now have code to execute if the values of those numbers are not the same.  The runtime engine should execute the “else” statement in this example.  We have now given the .NET engine 2 different blocks of code to execute based on a decision.  Let’s see how we can add even more.

Drag a another new Button onto the form and change the Text property to say “if with else if and else”.  Drag a new TextBox to the right of the Button control.  Double click the Button to create the event handler method and put the following code for the button:

 

int i = 103;
int j = 55;
int k = 103;

if (i == j)
  TextBox3.Text = "i and j are equal";
else if (i == k)
  TextBox3.Text = "i and k are equal";
else
  TextBox3.Text = "i doesn't match any of them";

Finally, I now added 3 different code paths into the “if” statement that C# can execute.  The runtime engine always starts at the first “if” to test the condition and make a decision.  If the first condition is NOT true, then it continues to the next condition which is the “else if” portion in this example.  You can have multiple “else if” portions, as many as you need.  If none of the “else if” conditions are true, then the “else” block will be executed.  In this example above, only the “else if” block of code will execute because the variables i and k have identical values.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Each time we explore a new C# topic on this website, I will have sample source code that you can download to supplement your learning.  I will always name my project folder the same as whatever the exercise name is, but I will append _csharpuniversity to the end of the folder name.  So for the first exercise in Getting Started with the language we explore Data Types and the project folder is called Lab1.  My associated sample source code is called Lab1_csharpuniversity and can be downloaded as a .zip file.

The following screencast video shows you how to open the sample ASP.NET project files that you download from this website using Microsoft Visual Web Developer 2008 Express.  This video shows you how to save a file called Lab1_csharpuniversity.zip from the website into your My Documents\Visual Studio 2008\WebSites folder.  That is the proper place to put your ASP.NET web projects on your hard drive.  Please note that I am using Winzip in this example video to unpack the .zip file.  You may not be using Winzip so that part may be a little different for you (e.g. you may be using Jzip or other browser software), but the idea is the same, you should unzip the files into the WebSites folder noted above.  Inside the project subfolder in the WebSites (in my example this folder is Lab1_csharpuniversity) will be all of the project files (.aspx, .aspx.cs, etc.).  Finally in the video, watch as I use the Open Web Site feature to open the project up in Visual Web Developer.

Click here to watch this video

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Click here to download the sample source code for this Data types lab exercise 

Go back to the Design view of your Default.aspx web page and add another Button and TextBox control on the next line.  Change the Text property of the new Button to “Show a floating point number”.  Double click that button to create the Button3_Click method.  Put the following code in the new method:

 

float f = 55.12f;
TextBox3.Text = f.ToString();

Here we have declared a floating point (or decimal) number.  Notice that I had to put a suffix of “f” following the number.  This is because by default, the compiler will assume that any decimal number is of type “double” which is a larger number.  Click the play button to run the project.  You can also run the project by clicking F5 which is a shortcut key for running the application.

Click on the new button when the web browser comes up and watch as it populates the TextBox control with the decimal number value.

Now I want you to go back to the Design view and drag another button onto the web page.  Change the Text to “Show a boolean”.  Double click on the new button to create the event method and inside the method put:

 

bool tedsbool = false;
TextBox4.Text = tedsbool.ToString();

Here we have declared a boolean type which only allows two different values “true” or “false”.  Also notice that we are repeatedly using a special method that a lot of .NET built in data types have which is the “ToString” method.  The ToString method converts the data type to a string or text type, so that it may be shown on the screen.

In C#, we call methods using the open and closing parentheses as in the ToString() example above.  The term method is synonymous with function, procedure and subroutine from other languages.

Just to ensure you are following along correctly, here is what the code in my C# looks like after I added 4 new event methods.  This is inside the file Default.aspx.cs and follows the empty Page_Load method:

 

protected void Button1_Click(object sender, EventArgs e)
{
 TextBox1.Text = "My first program";
}
protected void Button2_Click(object sender, EventArgs e)
{
 //This is a variable declaration in C#
int i;
//This is an assignment operation in C#
i = 33;
//This is an assignment operation in C#
TextBox2.Text = i.ToString(); 
}
protected void Button3_Click(object sender, EventArgs e)
{
 float f = 55.12f;
 TextBox3.Text = f.ToString();
}
protected void Button4_Click(object sender, EventArgs e)
{
 bool tedsbool = false;
 TextBox4.Text = tedsbool.ToString();
}

Notice that each button (1-4) has its own event handler method that gets executed when the corresponding button is pressed.

Finally to close out this exercise lesson in Data Types, in the Design view, add another Button and TextBox on a new line.  This time make the button say “Show a string”.  Create the event method.  Inside the method put:

 

string tedstring = "This is an example string!";
TextBox5.Text = tedstring;

This special data type called “string” is actually an alias for the System.String class from the Framework and holds text characters.  It is dynamic so you don’t have to declare how many characters you want to put in there before you use it.  The right side of the assignment operator where we have “This is an example string!” is what’s called a string literal.  This means you are hard-coding a text value for the string variable right into your code.  Also, since string variables are dynamic, you can always reassign the tedstring variable a different value further down in the code.  This applies for the other variable types that we experimented with in this exercise as well.  Here is an example where I reassign a string variable:

 

string tedstring = "This is an example string!";
tedstring = "A new value";
TextBox5.Text = tedstring;

If you run the program now, it will display “A new value” in the Textbox because I have reassigned the variable to a new value on the second line.  You only declare a variable once, but you can assign it many times, as much as is needed in your program.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

*Note: “web page” is synonymous with “web form” on this website and in all the examples.

Click here to download the sample source code for this Data types lab exercise  If you forgot how to open the files using Visual Web Developer, click here to learn How to open C# ASP.NET Website files.  Please use these files only as a reference.  You should go through the exercises yourself and create your own project according to the instructions in the exercise.

In the middle pane of Visual Web Developer you should see some HTML code if the Default.aspx tab is selected.  You are in the Source view.  At the bottom of that page, click on the Design view to be able to see the web page more like it will look when it runs in the browser.  In this Design view you can drag ASP.NET Server Controls onto the page and then customize how they look, as well as create code that will execute based on events that occur, such as button clicks.

On the left hand side of Visual Web Developer you should see the Toolbox, that contains a bunch of ASP.NET Server Controls.  Drag a Button control onto your Default.aspx page.  Drag a TextBox control to the right of the Button.

Double click on the Button control and that will automatically create a special method called “Button1_Click”.  This method will get called by .NET whenever this button is clicked on your web page, so you can put C# code in here, to tell the button what to do.

Paste the following code inside the Button1_Click method:

 

TextBox1.Text = "My first program";

Now to run your program, click the green play button at the top of the IDE.  The first time you run the website, you will be asked if you want to enable debugging.  Choose the Modify the Web.config file to enable debugging option and click OK.

Next, your web page should come up and show the Button and TextBox controls in your web browser.  Click on the button and watch as it populates text in the TextBox.  Congratulations, you have successfully run your first coding exercise in C#.  *Remember that to stop running your application and go back to the Visual Web Developer IDE so that you can keep working on your project, you must close the web browser window that was opened by Visual Web Developer when you clicked the green play button.  Once you close that web browser window, the Visual Web Developer changes back into edit mode so that you can continue working on your project.  If you don’t close that web browser window, you will notice that Visual Web Developer may not let you perform certain actions because it is not in edit mode.

Click here to watch an example video that shows you how to create the Button and TextBox controls, and create a Button click Method

Now let’s experiment with some different data types.  Close your web browser and go back to the Design view of the Default.aspx page in the IDE.  At the top of the middle pane in the IDE, you will see that there are different tabs: Default.aspx.cs and Default.aspx.  Click on the Default.aspx tab to bring up the web page view.  Another way to bring that up when you are looking at the source code is to right click on the source code and choose View Designer.  That takes you back to the tab where you were able to change how the web page looks and what controls it contains.

Place your cursor right after the TextBox control and hit Enter.  This will place the next control that you add onto the next line.  Now drag another Button and TextBox control onto the new line.  You should now have 2 buttons and 2 textboxes on your web form.

Single click on the new Button control that you added to select it.  In the Properties window which is usually in the lower right hand corner, change the value in the “Text” property to “Show an integer” without the quotes.  If you click back on the web page, you should see that the button looks different now and no longer says “Button” on it.

Double click on the new Button to create the event method.  It should be called Button2_Click.  Put the following code in there and then click the green play button to run the program again:

 

//This is a variable declaration in C#
int i = 33;
//This is an assignment operation in C#
TextBox2.Text = i.ToString();

Click on the new button and watch it populate the new textbox with the number 33.  The variable declaration shown above defines a new variable named “i”, with the type being a 32 bit integer number.  The “=” sign is the assignment operator and in this case we are assigning the value of 33 to the variable named “i”.  The // tells C# that you are putting a comment into the program.  A comment is simply notes or comments that are ignored by the compiler.  In other words, comments are not code, they are simply embedded documentation.  In some cases, you may find that putting comments above a line of code looks cleaner than putting it on the same line.  That is a matter of style.  Finally, I want you to notice that each line of code in C# ends with a semicolon “;”.  The semicolon lets the compiler know that it is at the end of a statement.  Some lines of code do not have semicolons at the end, and you will see examples of that on this website.  Those are situations where you are defining loops, method declarations, creating blocks of code inside conditionals and other scenarios.

Click here to watch an example video that shows you how to declare an integer

In the above example you could split up the variable declaration and assignment into 2 lines of code like this:

 

//This is a variable declaration in C#
int i;
//This is an assignment operation in C#
i = 33;
//This is an assignment operation in C#
TextBox2.Text = i.ToString();

Since this creates extra lines of code, I prefer to do the declaration and assignment in one line of code.  This is called initialization, which means that you declare the variable and give it an initial value.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Launch Visual Web Developer 2008 Express Edition.

Click File->New website

Choose ASP.NET Web Site from the templates at the top

At the bottom of the dialog, make sure that File System is the location and Visual C# is the language.

Click on the drop down box to the left of the Browse button at the bottom of the dialog.

Put your cursor at the end of the text and change the name of the application to Lab1.  It will look something like this depending on your file system structure:  C:\Documents and Settings\ted\My Documents\Visual Studio 2008\WebSites\Lab1

This is how you name your project when you first create it.  In this case our website project is called “Lab1″.  Click OK to have the IDE create the project for you.  You will get a skeleton application with one web page named “default.aspx”.

Click here to watch a sample video that shows you how to create your first web application project

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

The .NET Framework uses a non-language specific standard called the Common Type System (CTS) for all variable types.  The CTS standard ensures that every .NET language use a common set of variable types.  Since all .NET languages use a common set of types, they are easily integrated at runtime.  A C# program can easily call a VB.NET component and vice-versa.  So when you talk about C# variable types, you are really talking about .NET variable types.

This is important to understand because although the syntax of the C# language is different than VB.NET and others, the data types used are the same.  Every time you declare a variable type in C# like “int” for example, you are really declaring a .NET Framework type called Int32, which is a large 32 bit signed integer number.

Here are some of the most commonly used C# data types:
int - 32 bit signed integer
long - 64 bit signed integer
float - 32 bit floating point number
double - 64 bit floating point number
bool - true or false
string - series of text characters (almost every C# program has some)

When you declare any of these types in your program, C# transparently implements these data types as official .NET classes in the “System” Namespace as part of the Framework.  You will find that all data types in C# are actually classes, or objects, that contain methods and properties, but more about that later.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

When you are on MSDN documentation web pages, you have the option to only show C# examples throughout the help.  I recommend you change the language filter at the top of the web page; deselect the other languages so that only C# is checked.  There should be a little arrow button next to the words “Language Filter”.

 This will decrease the size of the web page and make it more readable.  It will also prevent you from looking at examples that don’t apply and incorrectly pasting code from the wrong language into your IDE.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

*You need to login to your Windows XP or Vista desktop as a user that had administrative privileges in order to perform these installations.

In order to get started with C#, you will need to download and install Microsoft Visual Web Developer 2008 Express Edition.  If you have the 2005 version, the code examples may work fine, but it all depends on what you are trying to do and what kind of project you are running.  I do understand that some folks don’t have a choice in their professional environment because the customer cannot make a move to 2008 right away and that is perfectly normal.  In any case, what you learn on this website will be useful for both versions since they are very similar.  Click here to download the Visual Web Developer 2008 Express Edition with SP1.  Scroll down towards the bottom of the page and click on the Download button next to vwdsetup.exe.  While you are installing Visual Web Developer, it may ask you if you want to install SQL Server 2008; I recommend that you say No and install that separately because it is a longer installation process with configuration that is necessary to smoothly integrate with your ASP.NET and ADO.NET applications.

For writing Class Libraries in C#, we will be using Microsoft Visual C# 2008 Express Edition.  The same things regarding 2008 versus 2005 apply here; they are very similar and you may not even notice any difference if you have used 2005.  Click here to download the Visual C# 2008 Express Edition with SP1.  Scroll down towards the bottom of the page and click on the Download button next to vcssetup.exe.

If you are working in a professional environment, you may be using the fully licensed Microsoft Visual Studio .NET 2008 or 2005 and that is fine as well.

As you install the products above, they will install the .NET Framework version 3.5 if you don’t already have it on your computer.  You should install the service pack 1 for the .NET Framework after all of your installs above have completed.  Click here to download the .NET Framework 3.5 Service Pack 1.

To work with the database examples on this website, please read the lessons in SQL Server Installation - Config.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques

Before you start with the lessons and examples on this website you need to know a few things about .NET and the various versions of the Framework.

The .NET examples used on this website are targeted for the .NET Framework version 3.5 and Visual Web Developer 2008 Express Edition.  That said, they may also work with older .NET versions.  The examples will also work with the full Visual Studio .NET IDE tool most of the time.  The full Visual Studio .NET however may look slightly different than the Express version in some of the screenshots used.  This is because the full Visual Studio .NET has additional features not available in the Express versions.

Also please note that the Express versions are separated into two separate products: Visual Web Developer and Visual C#.  Visual Web Developer is used for writing ASP.NET web applications and web services.  Visual C# is used for writing class libraries. 

Before you begin looking for books and online materials I will tell you a little bit about my experience with learning ASP.NET and C# and what I recommend for newbies.  First, there really is no single book, CD, or website that will teach you everything you need to know about ASP.NET and C#.  Some materials are geared towards helping you pass a certification exam, whereas other materials may advertise to teach you ASP.NET in 21 days or 24 hours.

Realize that each resource has its purpose and you will need to read from various resources and websites to learn ASP.NET and C# practically and be able to really use it.  Your journey will start here and I will walk you through everything you need, but just realize periodically I may temporarily point you to external sites in order to provide you with all the comprehensive quality information you need to succeed 110%.

You will also have to build on the examples that you find with some guidance from expert level ASP.NET/C# programmers like myself.  Let’s face it, “Hello World” just isn’t enough; you have to go beyond that and build on your learning incrementally.  That is what we will do here together and you will get better and better at it over time.  By combining the material on this website, external recommended material from free online resources, books that you like and advice from good programmers you know, you will be getting the complete set of tools to practically learn ASP.NET with C#.

In addition, there are pros and cons to the different styles of teaching ASP.NET and C#.  Some instructors start you off with hands-on exercises right away without any introduction to the .NET Framework.  Others use hands-on interaction later in the book or course, after many of the concepts have been reviewed in a classroom setting or book chapter.  I tend to prefer a hands-on approach with a little bit of introduction first.  I want the example exercises and lessons to be practical for you and not some code that you would throw away.  I want you to be able to implement a real ASP.NET with C# application and apply what you learn here immediately.

Finally, here is some motivational advice: don’t get frustrated along the way!  You will be presented with technical challenges and in some instances you may hit a brick wall.  I have seen students break through the brick wall, and others give up completely.  Please don’t be the one that gives up, you really can do it if you have the desire to learn and succeed.  I will also help you create and fully develop that desire so that you are fully driven.

ASP.NET is a really fun and wonderful programming platform.  It is the best web programming framework in the world because of its ease of use and powerful capabilities.  C# is a very logical and succint programming language that can be really fun if you approach it from the right mindset.

If you do feel at some point like you are just lost or cannot proceed, take a break, do some more reading or re-reading and then go back to your assignment later when you are fresh.  Sometimes just being fatigued can challenge your brain enough to affect your learning.  Also, don’t get too worried if you don’t understand every last detail about ASP.NET or C# in order to be successful with it.  You are going to be constantly learning new things so as long as you are always progressing, you will be in good shape.

Happy Coding and welcome to Amazing ASP.NET.  It’s great to have you here.

"Want the secret resource that beginning web programmers don't normally have access to? Want to start practicing with ASP.NET quickly and easily?"

Jump start your ASP.NET learning in a matter of minutes
Practice hands on with fully functional sample ASP.NET web sites
Master the most common ASP.NET programming techniques
Have tons of fun learning interactively
Improve at your own pace from the comfort of your computer

Click below to get started within minutes...
You too can MASTER ASP.NET Web Development Techniques