Home Page
"Join my free Amazing ASP.NET newsletter"
It's safe and easy to signup. You get:
  • Notified anytime a new article comes out
  • Technical step-by-step tutorials on all important ASP.NET topics
  • Expert guidance so you can reach unlimited ASP.NET success
  • Important ASP.NET news updates
Enter your Email

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. 

C# programs contain different types of or symbols that perform operations on variables of various types.  Some operators can perform mathematical operations such as addition or subtraction, whereas other operators can take two string variables and combine them into one.  One operator that we have seen in use as we experimented with data types is the assignment operator =.  The assignment operator is the most basic and widely used operator in the C# language.  When used in a C# statement, the assignment operator takes whatever expression is on the right hand side of the = symbol, evaluates it, and then puts the resulting value into the variable on the left hand side of the =.  Let’s take a look at some more commonly used operators.

Create a new website using Visual Web Developer and call the project Lab1_ext.  Go to the Design view for the file Default.aspx.  Drag a new Button onto the form and change the Text property to say “Addition operator”.  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 = 30;
int j = 10;
//Addition operator
int result = i + j;
TextBox1.Text = result.ToString();

Drag another Button onto the form and change the Text property to say “Subtraction operator”.  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 = 30;
int j = 10;
//Subtraction operator
int result = i - j;
TextBox2.Text = result.ToString();

Drag another Button onto the form and change the Text property to say “Concatenation operator”.  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:

string s1 = "Hello student,";
string s2 = " how are you?";
//string Concatenation operator
string result = s1 + s2;
TextBox3.Text = result;

Drag another Button onto the form and change the Text property to say “Increment operator”.  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 = 50;
//Increment operator
i++;
TextBox4.Text = i.ToString();

Drag another Button onto the form and change the Text property to say “Decrement operator”.  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 = 50;
//Decrement operator
i--;
TextBox5.Text = i.ToString();

Drag another Button onto the form and change the Text property to say “Addition assignment operator”.  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 = 50;
//Addition assignment operator
i += 5;
TextBox6.Text = i.ToString();

Drag another Button onto the form and change the Text property to say ”Concatenation assignment operator”.  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:

string s = "Hi ";
//Concatenation assignment operator
s += " there!";
TextBox7.Text = s;

Run the project using the green play button at the top of the IDE.  Click on the various buttons and see their outputs on the web page.  Notice that some of the operators such as the + symbol act as different types of operators depending on the data types that are used in the expression.  If the + symbol determines that a string type is being used in the expression, the C# language will perform a string concatenation or combination of two strings together.  Whereas, when numeric types are being used, the C# language will perform mathematical addition operations.  You should also note that the different operators accept variables instead of hard coded values so the code example above for the addition assignment operator could have been alternatively written as:

int i = 50;
int j = 5;
//Addition assignment operator
i += j;
TextBox6.Text = i.ToString();

Notice that a variable j is used instead of the hard coded value of 5.  This is important to understand because frequently in your coding, you will encounter situations where you don’t know the values of variables ahead of time so you will need to perform these types of dynamic expression operations.  Spend some time looking over other types of C# operators as well on the and experiment with those that you find interesting.

Click here to download the sample source code for this lesson

In order to effectively build web applications rich with user interactive server controls, you have to know how to properly solicit information from the application users.  The first step in achieving that is to develop a screen design with the appropriate server controls for your business application.  Each type of server control has its purpose and I describe some common uses below to help you determine which control to use for various situations.

To solicit text from the user that should be typed (e.g. a registration form Last Name field) use the control.  If you want the user to be able to enter multiple lines of input such as a Notes field, there is a property of the TextBox called TextMode that you can set to MultiLine.

If you want the user to choose an item from a simple list you have a couple of options: the and the .  The DropDownList is better in situations where you don’t want to show all of the available options on the screen at one time; the user has to click on the control to see all of the options.  The ListBox however is sizeable and shows multiple options on the screen without requiring the user to click; if the options are more than the size of the ListBox, a scroll bar will appear.  Also the ListBox allows for multiple concurrent selections so that user can choose more than one item at a time.

If you want the user to be able choose one option versus another use the control.  A similar server control for options is the control.  Both of these controls have a property called Checked which you can reference in the source code.  We will experiment with both of these controls and the Checked property in this lesson.

The RadioButton and CheckBox controls also are available as lists: and .  These are practical in situations when you want to display several options. 

If you want the user to execute a server side action such as saving data that was typed in a form, performing a search, or navigating to another page, you should use the control.  As far as buttons go, you have a few different choices: the standard Button, the and the .  The only difference between these is how they look.  All of them have the Click event and work just like a regular ASP.NET Button.  The LinkButton looks like a traditional Internet hyperlink.  The ImageButton is a bit more fancy in that you can reference an image file that you want to be clickable.  By clicking on the image, the user can trigger the Click event.

Create a new web form called Default5.aspx and go to the Design view.  Now let’s build our first real user input form.  We are going to build a job search registration form, one that may look similar to what you would see if you were registering on a job search website.  Click here to watch an example video for what we are going to do in the next several steps of this lesson.  *You will notice that as I drag server controls onto the web form, when I want to place a control on the next line, I click to the right of the control and then press the ENTER key.

Drag a Label onto the form.  Change the Text property to “Job Registration”.  Change the Font properties to Bold and the size Large.  Add two new lines.

Drag a Label onto the form.  Change the Text property to “First Name”.  Drag a TextBox next to the Label and change the ID to txtFirstName.  Add a new line.

Drag a Label onto the form.  Change the Text property to “Last Name”.  Drag a TextBox next to the Label and change the ID to txtLastName.  Add a new line.

Drag a Label onto the form.  Change the Text property to “State”.  Drag a DropDownList next to the Label and change the ID to ddlState.  Add three items into the control: California, Texas and Virginia.  To add items put your cursor over the control and a little button with > symbol appears.  Click that button and then click Edit Items…  Add a new line.

Drag a Label onto the form.  Change the Text property to “Industry”.  Drag a ListBox next to the Label and change the ID to lstIndustry.  Add three items into the control: Healthcare, Information Technology and Financial.  Adding items into the ListBox is similar to adding items into the DropDownList as you did above.  Add a new line.

Drag a Label onto the form.  Change the Text property to “Availability”.  Drag a RadioButton next to the Label and change the ID to rbnImmediately.  Change the GroupName property to “Availability” and the Text property to “Immediately”.  Drag another RadioButton and change the ID to rbnTwoweeks.  Change the GroupName property to “Availability” and the Text property to “Two Weeks Notice”.  Add a new line.  By making the GroupName the same for both of these RadioButtons, you ensure that the user can only click on one of them at a time.

Drag a CheckBox onto the form.  Change the ID to chkOver18.  Change the Text property to “Click here to certify that you are over 18″.  Add a couple of new lines.

Drag a Button onto the form.  Change the ID to btnRegister.  Change the Text property to “Register”.  Add a couple of new lines.

Drag a Label onto the form.  Change the Text property to “Output”.  Drag a TextBox next to the Label and change the ID to txtOutput.  Change the TextMode property to MultiLine.

When you are finished adding all the controls and editing their properties, your Default5.aspx form should look like this.
ASP.NET Job registration form

Double click on the btnRegister button to create the even handler method btnRegister_Click and paste the following code:

string NEWLINE = "\r\n";
string FirstName = txtFirstName.Text;
string LastName = txtLastName.Text;
string State = ddlState.SelectedValue;
string Industry = lstIndustry.SelectedValue;

txtOutput.Text += FirstName;
txtOutput.Text += " ";
txtOutput.Text += LastName;
txtOutput.Text += NEWLINE;

txtOutput.Text += State;
txtOutput.Text += NEWLINE;

txtOutput.Text += Industry;
txtOutput.Text += NEWLINE;

if (rbnImmediately.Checked == true)
    txtOutput.Text += "Immediately";
if (rbnTwoweeks.Checked == true)
    txtOutput.Text += "In Two Weeks";
txtOutput.Text += NEWLINE;

if (chkOver18.Checked == true)
    txtOutput.Text += "User is over 18";

At the top of the code, I declared some variables to hold the values of the user input controls.  For TextBox controls you can find out what the user typed into the control by using the Text property (e.g. txtFirstName.Text).  For the list controls you can use the SelectedValue property (e.g. ddlState.SelectedValue). 

Following the variables declarations, I display all the values for the different controls in the TextBox txtOutput by using the concatenation operator += which will append text into the control.  Notice that I use the Text property of the txtOutput control to display the values.  Finally for the RadioButton and CheckBox controls, I examine the Checked property to determine if the user selected the control by clicking on it.

Click here to download the sample source code for this lesson

Some of the server controls in ASP.NET have an event called Text Changed.  This event is fired by ASP.NET anytime a user changed the text contents in a control and press the TAB key or put the focus on another control.  This event allows you as the programmer to dynamically know if the user typed something and then your code can perform some actions based on that event.

Create a new web form named Default4.aspx and go to the Design view.  Drag two TextBox controls onto the web form and name the IDs txtSource and txtDestination accordingly.  Double click on the txtSource TextBox control and Visual Web Developer will create an event handler named txtSource_TextChanged.  Again notice the naming convention, ID appended with event type.  In the Method, type the following:

txtDestination.Text = txtSource.Text;

Go back to the Design view for the Default4.aspx page and we need to set a special property in order for this example to work.  Click on the txtSource TextBox control and change the AutoPostBack property to True.  This ensure that if something changes in that TextBox and the user presses TAB, the web browser will automatically post back the form or call the server to request the web page again.  If you don’t set that property, the web browser will not request anything from the web server and your txtSource_TextChanged event won’t fire.  To summarize the sequence of events that occur when the web page runs in our example:

First, when the page loads, ASP.NET will render two empty TextBox controls.  When the user types something into the first TextBox control and TABs off the field, the browser will request the web page from the server again (this is called a PostBack because the web form is “posting back” to the server).  When the server receives the request, it senses that the TextBox control’s contents have changed so it fires the txtSource_TextChanged event Method.  ASP.NET is handling all of this interaction between your web browser and the server behind the scenes.  This abstraction makes it very productive for web programmers because they can focus on programming their business logic and let ASP.NET handle all the HTML, Javascript and other technologies that the web application needs to work.

Click here to download the sample source code for this lesson.  

ASP.NET uses an event driven programming model.  This means that in order for code to run, an event must occur that triggers or tells ASP.NET to run an event handler Method.  An event handler method is a special type of Method in an ASP.NET web page that defines the actions that will occur when a particular event occurs.  So far, throughout the lessons we have experienced one of these types of events: the click event.  We saw that if you are in the Design view for a web form and you double click on a Button control, Visual Web Developer will automatically generate an event handler Method called Button1_Click.  Basically an empty Method is generated and Visual Web Developer lets you put whatever code you want into that event handler.  Notice the naming convention that Visual Web Developer when it generates the event handler Method.  The first part of the name is the ID for the server control: Button1.  The second part of the name an underscore appended with the event type: Click.  This convention helps you as the developer know when that Method will be called by ASP.NET.  In this case, the click event fires when a user single clicks on the Button control.

ASP.NET supports different types of events for the various server controls but there are some very common events and those are the ones we will focus on in the next few lessons.  The first of these events that we will practice with is the Page Load event.  This event fires every time you navigate to an ASP.NET web page in your web browser.  When type a .aspx page in your browser’s URL window or click on a link that takes you to an .aspx page, you are triggering the Page Load event on the web server at the time the page is requested.

Create a new web form called Default3.aspx.  Drag a TextBox onto the web form and change the ID to txtHello.  Double click on a white area of the web form where there are no server controls.  Visual Web Developer should take you into the Page Load event Method Page_Load.  In there, put the following:

txtHello.Text = "Message from the Page Load event";

Go back to the Design view for Default3.aspx and drag the right side of the TextBox control to the right (about 500px) in order to make it larger; this way you will be able to read the entire message “This info was put…” when the page runs.  Run the application and notice that when Default3.aspx comes up, the message is already in the TextBox.  Now close the browser and go back to the Design view for Default3.aspx and drag a Button control to the left of the TextBox.  Change the ID property of the Button to btnPutmessage and the Text property to “Change the message”.  Double click the Button to create the event handler Method.  *Notice that the event handler is called btnPutmessage_Click.  In the code put the following:

txtHello.Text = "Message from the Button Click event";

Run the application again and this time click on the Button.  Notice that the message in the TextBox changes because ASP.NET fired the btnPutMessage_Click event when you clicked the Button.

ASP.NET server controls each have a property called the ID.  The ID property defines a unique name for the server control.  You cannot have two server controls on the same web form with the same ID.  The ID is what you use in the C# source code behind .cs file to reference a control on a web form.  If you are unsure what the ID of a control is, click on a control in the Design view and scroll down the Properties window until you see (ID).

When you drag a control onto the web form, the IDE creates a default ID for your control.  It is a good idea to immediately rename your control’s ID right after you put it on the form.  You should name it something meaninful to your application and use a naming convention prefix.  For example, if you plan to use a TextBox to store a user’s last name, name the TextBox control’s ID to “txtLastname” or something similar.  It doesn’t matter what the particular convention is that you use, but be consisent across your application so that your code is more readable and easier to understand.  It is very difficult to debug and maintain a program where the control names are TextBox1, Button1, and so forth.

I like to use simple prefixes appended with a meaninful name for my server control IDs.  Here is a list of some prefixes that I use for my server controls and their meaning:

txt = TextBox (e.g. txtLastname)
btn = Button (e.g. btnSavedata)
ddl = DropDownList (e.g. ddlAccounts)
chk = CheckBox (e.g. chkAdmin)
rb = RadioButton (e.g. rbSpringsemester)

The prefix helps your source code become more maintainable because you can instantly know what kind of server control you are dealing with when you see and modify the code.

Click here to download the sample source code for this lesson.  

In the previous lesson Intro to ASP.NET server controls, we covered how to change the appearance of server controls such as Buttons, TextBoxes and DropDownLists by using the Properties window.  There are situations where you need to change the appearance or behavior of server controls dynamically at runtime; this is accomplished by using C# in the code behind .cs file.  You can do a number of different things using code such as hiding controls, changing their color, changing their font, and even setting focus of the cursor to a particular control.

Let’s do an example.  Create a new web form named Default2.aspx and go to the Design view.  Drag a Button onto the web form. Drag a TextBox next to the Button.  Drag a DropDownList next to the TextBox.  Finally, drag a Label next to the DropDownList.  Double click the Button to create a new event handler method and put:

DropDownList1.Visible = false;
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Font.Size = FontUnit.XSmall;
TextBox1.Focus();

Click play to run the application and click on the Button once the web page comes up.  Notice that the DropDownList disappears, the Label’s size and color changes and the cursor gets placed inside the TextBox control.

Click here to download the sample source code for this lesson.  

ASP.NET is the Microsoft .NET web programming model.  It contains web oriented class libraries, controls and design paradigms.  An ASP.NET application contains one or more Web Forms (or Web Pages).  Each Web Form contains server controls.  Server controls are basically things that you see on a web page when the application executes, such as buttons, text boxes, drop down lists, labels, etc.  “Server” controls are named as such, because the ASP.NET web engine runs the event code for the controls on the server (not in the user’s web browser such as with Javascript).  This allows ASP.NET web programmers to define event handler Methods for controls and manipulate control properties in pre-compiled C# code that runs on the server.  This server side control paradigm is very powerful for programmers because it makes building web pages very dynamic, easy to do and easy to maintain.  With ASP.NET, there is no longer a need to use Response.Write statements to generate HTML code for the browser (classic ASP programmers, JSP programmers and PHP programmers will appreciate this).  ASP.NET generates HTML code for you at runtime when you use server controls.

In previous exercises we had gotten some basic experience with server controls when we used Button and TextBox controls.  Let’s spend some time practicing with some additionals controls and their properties.  Create a new website called Lab6.  On the default.aspx web form go to the Design view.  From the Toolbox window, drag the following controls onto the form one by one: a Label, a TextBox, a Button, a LinkButton, a DropDownList, a CheckBox, and a RadioButton.

Now let’s manipulate some of the properties for these server controls and see how their appearance changes.  In ASP.NET whenever you want to change the appearance or behavior of a server control, you can manipulate the control’s properties.  Every server control has a unique set of properties, however a lot of the controls share some common properties such as the Text property which defines what text appears on the control during runtime.

Click on the Label control that you put on the form and change the Text property to “My First Label”.  Change the Font->Bold property to True.

Click on the TextBox control and change the Font->Italic property to True.

Click on the Button control and change the BackColor property to “Yellow”.

Click on the LinkButton control and change the Text property to “My First Hyperlink”.

Click on the DropDownList control and change the Items property.  To add items into the DropDownList, click on the Items property and then click on the ellipses (…)  The ListItem Collection Editor window should come up.  This window lets you enter whatever values you want shown in the drop down list.  Click the Add button.  In the Text property type in “My first list item”.  Click the Add button again and in the Text property type in “My second list item”.  Click the OK button to apply the changes.

Click on the CheckBox control and change the Checked property to True.

Click on the RadioButton control and change the BorderStyle property to Solid.

Now that you have finished modifying all of these property values, run the application and pay attention to the following characteristics about the controls you added to your web form:

The label shows up with bold font.  If you type some text into the TextBox, it is in italics.  The button is yellow.  You have a hyperlink that says “My First Hyperlink”.  There is a drop down list with the two items that you entered into the list items editor earlier.  The radio button has a solid border box around it.

By using the property editor you can change the appearance of any server controls on your web forms.  In the next lesson, we will learn how to modify the appearance of server controls using C# code and more about a special ASP.NET event called Page Load.

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

We saw in the previous exercises that Classes can contain Methods.  Classes can also contain what are called Instance Variables.  These types of variables are also referred to as Class Variables and Member Variables.  Instance variables are declared at the top of the Class and can be used by all the Methods inside the class.  Instance variables are a good way for Methods in the Class to be able to share information with each other, kind of like global variables.  Instance variables are also used to store state because when you instantiate and object of a Class (using the new keyword), the instance variables will keep whatever information is stored in them until the object variable goes out of scope.  As you practice more with C# you will understand this concept better by experience.

Let’s declare some instance variables in the Class Arithmetic.  At the top of the Class, above the “public Arithmetic()” declare the following 2 variables:

 

int mNumber1;
int mNumber2;

Then add a new Method:

 

public Arithmetic(int iNum1, int iNum2)
{
 mNumber1 = iNum1;
 mNumber2 = iNum2;
}

Make sure to leave the existing Constructor Arithmetic as is, you should now have 2 Methods named Arithmetic.  In the example above, I am taking the parameters iNum1 and iNum2 and storing the values of those variables in the instance variables mNumber1 and mNumber2.  Now add a new AddTwoNumbers Method:

 

public int AddTwoNumbers()
{
 return mNumber1 + mNumber2;
}

You should have 2 Methods named AddTwoNumbers: one that takes arguments and the new one that does not.  In contrast to the old AddTwoNumbers, this new one doesn’t require any arguments, but simply adds the two instance variables together and returns the result.  Now we are going to practice calling the new Constructor and using the instance variables.  Create a new web form called Default2.aspx.  Add a Button and TextBox to the form.  Change the Text for the Button to say “Call Class constructor”.  Double click the Button and put the following:

 

Arithmetic mynewclass = new Arithmetic(100, 200);
int iResult = mynewclass.AddTwoNumbers();
TextBox1.Text = iResult.ToString();

On the first line above, I am calling the Class constructor and passing two numbers: 100 and 200.  Once I do that, the mynewclass object is going to keep the values 100 and 200 in the instance variables.  Then when I call AddTwoNumbers() on the next line, that Method adds the two instance variables and returns the result of that operation.  This is in contrast to the prior lessons where I was calling the other version of the AddTwoNumbers Method that takes 2 arguments.  In this example, the Constructor Method Arithmetic and the AddTwoNumbers Method are sharing the instance variables.

Here are some important things to note about this lesson.  First notice that my Class Arithmetic has 2 Constructors and I can call either one when I instantiate the Class:

 

Arithmetic mynewclass = new Arithmetic();

OR

 

Arithmetic mynewclass = new Arithmetic(100, 200);

Also notice that there are two versions of the AddTwoNumbers Method as well and I can also choose which one to use.  Having more than one version of a Method is called Overloading.  Even though I can have more than one Method with the same name, each has a unique signature or set of parameters.  I CANNOT have two Methods with the same name and the same set of parameters, this is not allowed.  Each Method has to have its own distinct set of parameter types.  Experiment with this on your own and you will see what I mean.

Click here to download the sample source code for this Public versus Private Methods lab exercise 

Classes can contain both public and private Methods.  Methods that are declared as public can be called from outside the class and inside the class (by other Methods in the class).  In the previous exercise Calling User defined Classes, the Method AddTwoNumbers is a public Method.  That is why I was able to call it from my ASP.NET web page Default.aspx.

Methods that are declared as private CANNOT be called from outside the class, so by design they are hidden to the external program.  Private Methods can only be called from inside the class by other Methods in the class.  Let’s look at an example of a private Method.  Add the following Method to the Arithmetic Class from the previous example:

 

private int MultiplyTwoNumbers(int iNum1, int iNum2)
{
 return iNum1 * iNum2;
}

Now go back to the code for the Button click (Button1_Click) in Default.aspx.cs and try to call the Method MultipleTwoNumbers:

 

int iMultiplyResult = mynewclass.MultiplyTwoNumbers(50, 20);

If you right click on the project name in the Solution Explorer and choose Build Web Site you will get a compiler error: “Arithmetic does not contain a definition for MultiplyTwoNumbers”.  This is because that Method is Private, thus it cannot be accessed from outside the Class Arithmetic.

Usually private Methods are used in situations where you have a lot of redundant code throughout different Methods in a Class and you want those Methods to share some common code.

Click here to download the sample source code for this Calling User defined Classes lab exercise 

This exercise is a continuation of Creating User defined Classes.  In that lesson, we practiced creating a new Class and we put a Method in the class called AddTwoNumbers.  Now let’s see how to actually use that Class by calling the Method from our ASP.NET web page Default.aspx.  Open Default.aspx and go to the Design view.  Drag a Button and a TextBox onto the web form and change the Text property of the Button to say “Call User defined Class”.  Double click the Button to create the event handler and put:

 

Arithmetic mynewclass = new Arithmetic();
int iResult = mynewclass.AddTwoNumbers(50, 20);
TextBox1.Text = iResult.ToString();

In order to call a Class you first have to Instantiate an  of the Class.  This terminology means that you have to declare a variable with the type set to your Class name.  In the above example, notice that I did that “Arithmetic mynewclass”.  mynewclass is a variable of type Arithmetic.  The second part of instantiating an Object is to apply the “new” keyword after the assignment operator “= new”.  Finally, the last step is to put the Class name again with open and closed parentheses “Arithmetic()”.

Once you do this instantiation, you can then call the Methods that are available in the Class.  Creating your own Class is sometimes referred to as Creating a User Defined Type since a Class is a type in C#.  Notice earlier I said that mynewclass is a variable of type Arithmetic.  Arithmetic is a User Defined Type.  In order to call a Method that is inside the Class all you have to do is use the variable that you declared (in my case mynewclass) and put a . (period) after it followed by the Method name “mynewclass.AddTwoNumbers”.  Then you can pass parameters to the Method inside parentheses.  Since the Method AddTwoNumbers returns an Integer, I declared a variable to store the result of the Method call.

Click here to download the sample source code for this User defined Classes 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 C# Methods are declared and used, it’s time to move on to .  A User defined Class is a way to group a set of related Methods and variables together.  Just like Methods, Classes are a good way to further organize and reduce redundancy in your program’s soure code.  In C#, almost everything is built around Classes, even some of the language data types such as String, which is actually a Class called .

Let’s take one of the Methods “AddTwoNumbers” we had created in the prior exercise “Creating and using Methods” and move it into a new Class.  Create a new website using Visual Web Developer and call the project Lab5.  In the Solution Explorer, right click the project name and choose “Add New Item”.  From the templates list, choose “Class” and then enter “Arithmetic” for the name of your new Class.  Click Add to finish.  Click here to watch a sample video on how to Create a new Class.

Notice that Visual Web Developer will create an empty Class for you and there is only one Method in the Class right now.  That Method is named “Arithmetic” and notice that it has the same name as the Class itself.  This is a special Method called the Constructor.  More about Constructors in another lesson.  Underneath the Constructor Method Arithmetic, put the following new Method:

 

public int AddTwoNumbers(int iNum1, int iNum2)
{
 return iNum1 + iNum2;
}

Make sure that you put the code after Arithmetic and NOT inside it.  You should now have 2 methods in your Class: Arithmetic and AddTwoNumbers.  A Class can contain as many Methods as you like, generally all of the Methods in a particular Class should be related in some way.

Click here to download the sample source code for this Methods 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 the C# list data types work, it’s time to move on to .  Methods are blocks of code that perform some actions and can return back a result.  Methods are also called Functions or Procedures in other languages.  Methods are a good way to organize your code into separate functional areas in order to make it more maintainable.  Methods can also help you reduce redundancy by taking identical blocks of code that you have in multiple places of your program and keep them in one central place.

Create a new website using Visual Web Developer and call the project Lab4.  Go to the Design view for the file Default.aspx.  Drag a new Button onto the form and change the Text property to say “Execute a Method”.  Drag a new TextBox to the right of the Button control.  Double click the Button to create the event handler method.  Replace the code in the method Button1_Click with the following:

 

protected void Button1_Click(object sender, EventArgs e)
{
 int iResult = AddTwoNumbers();
 TextBox1.Text = iResult.ToString();
}
int AddTwoNumbers()
{
 int iNum1 = 50;
 int iNum2 = 20;

 return iNum1 + iNum2;
}

Let’s go over how to declare a Method.  A Method declaration consists of three parts:
int AddTwoNumbers()
First is the return type.  In the example above, the return type is “int” or Integer, so I declared that my Method will return a number.
Second is the name of the Method, which is “AddTwoNumbers” in my example.
The last part of a Method declaration is a list of parameters or arguments to the Method.  The parameters are specified inside parentheses and are comma separated.  We will see an example of how to specify parameters later in this exercise.  In my example I do NOT have any Method parameters so you only see open and closed parentheses following the Method name ().

Now let’s discuss the contents of my Method AddTwoNumbers.  AddTwoNumbers is a very simple Method consisting of three lines of code.  Inside the Method I declare and initialize two variables iNum1 and iNum2.  I then add the two numbers together using the addition operator + and return the result of the addition to the Method caller.  Since I declared that my Method will return a number, it is mandatory that I have a “return” statement in my Method.  If I don’t put a “return” statement, the source code compiler will throw an error. 

In order to use my Method I simply put the name of the Method AddTwoNumbers followed by parentheses in the code block where it is needed.  Using a Method is also sometimes referred to as “calling the Method”, so the block of code that ”calls” the Method is thus referred to as the “Method caller”.  In my code example above, the Method caller can be found on the following line inside Button1_Click:
int iResult = AddTwoNumbers();
Notice that I called the Method by using the expression “AddTwoNumbers()”.  Since the Method returns a number I assigned the expression to a variable named “iResult” which is an Integer.  Finally I showed the result of the addition in a Textbox control.

Now let’s do an exercise where we declare a Method that doesn’t have any return type.  This type of Method is used when you want the Method to perform some actions, but don’t need any data back from the Method.  Create a new form called Default2.aspx.  In case you forgot how to do this, click here to watch an example video.  Go to the Design view and drag a Button onto the Form.  Change the Text of the button to say “Execute a Method with NO return”.  Drag a Textbox onto the Form.  Double click the Button to create the event handler and put the following:

 

protected void Button1_Click(object sender, EventArgs e)
{
 int iNum1 = 50;
 int iNum2 = 20;

 int iResultNumber = iNum1 + iNum2;
 DisplayResult(iResultNumber);
}
void DisplayResult(int iResult)
{
 TextBox1.Text = iResult.ToString();
}

In the above example I created a Method named DisplayResult.  This time around however my Method does NOT return any data so I had to put “void” for the return type.  Another difference in this example is that my Method takes one argument “iResult” which is an Integer.  This means that whenever my Method is called, I have to pass a number to the Method.  You can see that I did that in my example on the line:
DisplayResult(iResultNumber);
Since my Method does not return any data, I did not use the “return” keyword in the Method.

Let’s do an example with a Method that takes multiple arguments.  Create a new form called Default3.aspx.  Go to the Design view and drag a Button onto the Form.  Change the Text of the button to say “Execute a Method with multiple arguments”.  Drag a Textbox onto the Form.  Double click the Button to create the event handler and put the following:

 

protected void Button1_Click(object sender, EventArgs e)
{
 AddTwoNumbersAndDisplayResult(50, 20);
}
void AddTwoNumbersAndDisplayResult(int iNumber1, int iNumber2)
{
 int iResultNumber = iNumber1 + iNumber2;
 TextBox1.Text = iResultNumber.ToString();
}

Notice how this time I created a new Method named “AddTwoNumbersAndDisplayResult” and it takes 2 arguments iNumber1 and iNumber2.  To declare multiple arguments, you simply separate the argument variable names with a comma.