Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Using functions

From: ASP.NET Essential Training

Video: Using functions

As your ASP.NET web pages become more complex, it's useful to be able to break out functionality into separate subroutines or functions. Once again both the C# and Visual Basic languages support this feature. I will describe here how to create a function and how to call it using both languages. I'll start again with C#. I'll open the file ProgrammingCSharp.aspx and then I'll save it under a new name, selecting File > Save As and I'll name the file FunctionsCSharp.aspx. When you declare a function in C#, you start with an access modifier.

Using functions

As your ASP.NET web pages become more complex, it's useful to be able to break out functionality into separate subroutines or functions. Once again both the C# and Visual Basic languages support this feature. I will describe here how to create a function and how to call it using both languages. I'll start again with C#. I'll open the file ProgrammingCSharp.aspx and then I'll save it under a new name, selecting File > Save As and I'll name the file FunctionsCSharp.aspx. When you declare a function in C#, you start with an access modifier.

The access modifier determines the availability of the function. If you are placing the function in the same page in which it's called, you can declare it as private. If the function should be available from both this page and from any pages that are derived from this page, that is, in object oriented terms that are subclasses of this page, you should use the access modifier protected and if you want the function to be callable from anywhere in the application, you can use an access modifier of public.

There are other access modifiers available but those are the three that are typically used most often: private, public and protected. In this example, I'm going to be calling the function from within the same page but because I might want to use this page later on as the basis of another page I'll typically use the access modifier protected. So I start off with the protected keyword. Next, I indicate the data type of a value that the function is going to return. If the function is simply going to take some action but not return a value, you put in the keyword void with the lowercase v. But if the function is going to return a value, you use the data type in this position.

I am going to create a function that returns an integer, so I'll use the Int data type. Next, you put in the name of the function, which I'll call AddValues. In C#, you always put in parentheses at the end of the function name, regardless of whether the function can receive values. This particular function is going to receive two values or arguments. I'll name them Val1 and Val2, and I'll data type them both as integers. So I'll use the C# syntax, Int, then the name of the variable, Val1, then a comma and the second argument, Int again, and Val2 and then I close the function signature by putting in the closing parentheses. After the function signature and within the braces, you put in the code that you want to execute. Because I said that I was going to be returning an integer, I must return a value and you do that with the Return keyword.

I will return the results of this expression, Val1 plus Val2. Notice that you don't need parentheses around that expression. You can put them in if you prefer. Also notice that the plus operator in C# is used both for mathematical addition and for concatenation of strings which I have already done in other videos. This is called Operator Overloading, the reuse of an operator for more than one purpose. So that's my custom function, AddValues. Now, I'll go up to my testing function, runButton_Click, and I'm going to clear a variable called Total, once again an integer, and I'll get its value by calling my AddValues function.

Notice that Visual Web Developer already knows that the function exists and offers it in the list of functions that I can call. And after the cursor's on the function, I'll type in an opening parentheses. Visual Web Developer auto completes the function name and I'll pass in two integer values, 5 and 3 separated by commas. Next, I'll use my Output function and display the result. I'll start with the literal string, the total is, and then the plus operator to concatenate the result and I'll output the value of the variable.

I'll save my changes and run the code. I'll click the Run Code button and I'll see the result, the total is 8. So in C#, when you declare the function, you put in the access modifier, the data type and the function name. Then you declare the arguments or the parameters that you can pass into the function in a comma delimited list and each of the parameters gets a data type as well. If your function is declared as returning the value, you must return a value otherwise the compiler will complain.

Now let's do the same thing in Visual Basic. I'll open the file ProgrammingVB and I'll save it under a new name and I'll name the new file FunctionsVB.aspx. In Visual Basic, you declare functions differently depending on whether they are returning a value or not. For functions that are not going to return a value, you declare them using the keyword Sub for subroutine. These are the kinds of functions that I'm already using. The Output, runButton_Click and clearButton_Click functions don't return values; they just take certain actions and so we use the Sub keyword.

If on the other hand, you want to create a function that does return a value, you use the keyword function. The access modifier rules are the same as per C#. You can create subroutines and functions that are protected, public and private. Typically, if you are going to use the function within the current page, you use protected. So I'll start off with the access modifier protected. Then I'll put in the keyword function. Next, you put in the name of the function. I'll name it AddValues again and just as in C#, you declare a list of the values, the arguments that you want to accept in a comma delimited lis. For each argument, you can receive it by reference or by value.

There are certain more complex rules that apply to certain data types. In this case, I'm going to be receiving variables by value, which means that if I change the value within the function, it won't affect the value that was passed in. I'll name the argument Val1 and I'll declare the data type as integer. So, that's the first variable. Now, because the amount of code is going to be fairly wide, I'd like to add code on the next line. In Visual Basic, you can't just go down to the next line like you can in C#. You have to explicitly tell the complier, I'm continuing on the next line. You do that with the underscore character.

I will declare the second argument, once again saying that I'm receiving the argument by value. I'll pass in the name of the argument and once again set up the data type. At the end of the function declaration, you would then declare the data type of the value that's going to be returned. I'll use the keyword As and then Integer. So in C#, you declare the data type of the function before the function name. In Visual Basic, you declare it after the function name. When I press Enter, Visual Web Developer automatically puts in the ending code for the function, which is the words 'End function.' Now, just as in C#, I'm going to return a value. So I'll put in the Return keyword, which is done with uppercase R, and then I'll return the value val1 + val2. So there is my completed function. I'll go the runButton_Click function and I'll use it. I'll declare a variable named Total, I'll set its data type to integer and then I'll call my function AddValues and I'll pass in literal values of 5 and 3.

Then I'll output the result using my output function and once again I'll combine the literal string 'The total is' and then I'll concatenate the total variable using the ampersand. I'll save the changes and I'll run the page, I'll click the Run Code Button and once again I see the result. The total is 8. So let's review again some differences between C# and Visual Basic. In C#, when you declare a function, it's always a function. The syntax is pretty much the same regardless of whether you are returning a value. If you are not returning a value, you use the void keyword before the function name and if you are returning a value, you put in the specific data type.

In Visual Basic, if you are not returning a value, it's called a Sub or a subroutine or if you are returning a value, it's called a function and you declare the functions return data type after the function and after the arguments using the As keyword. Regardless of which language you are using, you use the Return keyword to return a value and as always, in C#, you include the semicolon at the end of the line to terminate the statement and in Visual Basic you don't. Finally, to point out one other very critical bit of difference between Visual Basic and C#, in C# white space such as line feeds and tabs are pretty much ignored.

In Visual Basic, the end of line is taken as the end of statement unless you explicitly indicate that you are continuing onto the next line using the underscore character, known here as the continuation character.

Show transcript

This video is part of

Image for ASP.NET Essential Training
ASP.NET Essential Training

79 video lessons · 51167 viewers

David Gassner
Author

 
Expand all | Collapse all
  1. 18m 44s
    1. Welcome
      1m 42s
    2. Prerequisites
      2m 21s
    3. Using the exercise files
      1m 32s
    4. Upgrading exercise file websites for ASP.NET 4.5 (NEW)
      2m 40s
    5. What's new in ASP.NET 4 (NEW)
      3m 48s
    6. What's new in ASP.NET 4.5 (NEW)
      3m 23s
    7. What's new in this course update (NEW)
      3m 18s
  2. 33m 34s
    1. Understanding how ASP.NET works
      5m 52s
    2. Installing Microsoft Visual Web Developer 2008
      3m 43s
    3. Installing Visual Studio Express 2012 for web (NEW)
      2m 12s
    4. Hello World: Creating your first ASP.NET web site
      4m 28s
    5. Creating pages with dynamic output
      7m 39s
    6. Understanding the development web server
      4m 49s
    7. Exploring the development environment
      4m 51s
  3. 40m 2s
    1. Understanding Microsoft SQL Server
      5m 47s
    2. Installing SQL Server Express
      6m 51s
    3. Exploring SQL Server Management Studio Basic
      4m 23s
    4. Creating a new database
      8m 51s
    5. Connecting to the database in ASP.NET
      5m 35s
    6. Testing SQL queries
      3m 53s
    7. Presenting a dataset in an ASP.NET page
      4m 42s
  4. 25m 31s
    1. Understanding ASP.NET web form pages
      5m 51s
    2. Separating presentation and logic with code files
      4m 17s
    3. Adding web form controls to a page
      5m 25s
    4. Handling postback data in a web form page
      5m 50s
    5. Using data binding expressions
      4m 8s
  5. 48m 37s
    1. Creating a testing environment
      4m 40s
    2. Declaring and using a simple variable
      6m 14s
    3. Declaring and using a complex object
      6m 16s
    4. Using loops
      6m 52s
    5. Using functions
      9m 25s
    6. Using trace statements
      4m 47s
    7. Debugging with breakpoints
      5m 45s
    8. Commenting code
      4m 38s
  6. 17m 43s
    1. Creating web controls
      5m 53s
    2. Registering a user control on a web form page
      3m 25s
    3. Registering controls globally in the web.config file
      3m 53s
    4. Adding public properties to a web control
      4m 32s
  7. 19m 7s
    1. Understanding Cascading Style Sheets (CSS)
      5m 36s
    2. Attaching external CSS files
      3m 12s
    3. Defining a CSS selector
      6m 10s
    4. Using CSS class selectors in server controls
      4m 9s
  8. 30m 34s
    1. Presenting data with the GridView control
      5m 49s
    2. Controlling GridView paging and appearance
      5m 46s
    3. Editing data with the GridView control
      6m 57s
    4. Presenting data with the DataList control
      5m 42s
    5. Formatting data with binding expressions
      6m 20s
  9. 36m 46s
    1. Using the DetailsView control
      7m 33s
    2. Inserting data with the DetailsView control
      6m 36s
    3. Redirecting page requests
      9m 39s
    4. Creating an update page
      6m 20s
    5. Linking to update pages from the list page
      4m 3s
    6. Deleting database records
      2m 35s
  10. 22m 15s
    1. Customizing forms with item editing templates
      6m 7s
    2. Adding validator controls to a form
      6m 40s
    3. Controlling the validation error message display
      6m 24s
    4. Using the ValidationSummary control
      3m 4s
  11. 29m 49s
    1. Creating a query with joined tables
      8m 6s
    2. Replacing control style properties with CSS
      5m 50s
    3. Creating a CSS file for printing
      3m 14s
    4. Suppressing elements in printed web pages
      5m 47s
    5. Selecting data for a report
      6m 52s
  12. 11m 14s
    1. Understanding ViewState and managing postbacks
      4m 36s
    2. Using session variables
      6m 38s
  13. 20m 57s
    1. Turning on forms authentication
      1m 51s
    2. Creating a page to log in users
      4m 18s
    3. Creating a page to set up new users
      4m 6s
    4. Understanding the security database
      3m 27s
    5. Configuring security in the web.config file
      2m 59s
    6. Creating a page to log out users
      4m 16s
  14. 27m 56s
    1. Installing IIS on Windows XP
      6m 32s
    2. Installing ASP.NET 3.5 on Windows XP
      1m 39s
    3. Deploying a site on Windows XP
      5m 9s
    4. Installing Information Internet Services (IIS) on Windows Vista, Windows 7, and Windows 8
      1m 56s
    5. Configuring ASP.NET 3.5 on Windows Vista
      2m 15s
    6. Deploying an application on Windows Vista
      3m 29s
    7. Scripting a database for deployment
      3m 36s
    8. Exporting database scripts in SQL Server Management Studio 2012 (NEW)
      3m 20s
  15. 2m 0s
    1. Where to go from here
      2m 0s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed ASP.NET Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.