• Getting started with Visual Basic .NET Language
  • Environment Setup
  • Program Structure
  • Basic Syntax
  • Functions and Subs
  • Classes and Objects
  • Module Statement
  • Constructors
  • Access Modifiers
  • For Next Loop
  • For Each Loop
  • While End Loop
  • With End With Statement
  • Exit Statement
  • Continue Statement
  • GoTo Statement
  • Conditional Statements
  • Select Case
  • Collections
  • Exception Handling
  • File Handling
  • Windows Forms Application
  • Basic Controls
  • Events Handling
  • Inheritance
  • Polymorphism
  • Abstract Class
  • Regular Expressions
  • Database Operations
  • BackgroundWorker
  • ByVal and ByRef keywords
  • Connection Handling
  • Data Access
  • Debugging your application
  • Declaring variables
  • Dictionaries
  • Disposable objects
  • Error Handling
  • Extension methods
  • File/Folder Compression
  • Google Maps in a Windows Form
  • Introduction to Syntax
  • Multithreading
  • NullReferenceException
  • OOP Keywords
  • Option Explicit
  • Option Infer
  • Option Strict
  • Reading compressed textfile on-the-fly
  • Short-Circuiting Operators (AndAlso - OrElse)
  • Task-based asynchronous pattern
  • Type conversion
  • Unit Testing in VB.NET
  • Using axWindowsMediaPlayer in VB.Net
  • Using BackgroundWorker
  • Using Statement
  • Visual Basic 14.0 Features
  • WinForms SpellCheckBox
  • Working with Windows Forms
  • WPF XAML Data Binding

VB.NET Database Operations

Fastest entity framework extensions.

Nowadays, you can't imagine any application without a database. If your application needs to access data from the database, you will need to perform some database operations.

  • In any programming language, accessing Data from a database is one of the important aspects.
  • It is an absolute necessity for any programming language to have the ability to work with databases.
  • VB.NET can work with a majority of databases, the most common database is Microsoft SQL Server.

SqlConnection

VB.NET provides a SqlConnection class that represents a connection to a SQL Server database, it cannot be inherited.

  • A SqlConnection object represents a unique session to a SQL Server data source.
  • With a client/server database system, it is equivalent to a network connection to the server.
  • It is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database.

To use these functionalities, we need to install System.Data.SqlClient NuGet package by running the following command in Package Manager Console .

Create Database

To create a database, let's open the SQL Server Object Explorer , expand the SQL Server and right-click on the Databases and select the Add New Database .

image

It will open the Create Database dialog.

image

Enter the database name such as MyTestDb and click the Ok button. Now right-click on the newly created database and select New Query... It will open the query editor, let's run the following script in the query editor.

It will create a table with the name Authors and add three records to that table. To check the data in the database table, right-click on the Authors table in SQL Server Object Explorer .

image

Select the View Data option, and it will display all the records.

image

Connect Database

To connect to the SQL database, you can use the following code.

The above code will create a new connection to the SQL Server database that will be connected using the connection string. To ensure that connections are always closed, open the connection inside of a using block.

Read Data From Database

Let's add some code to read data from the database we created.

Let's run the above code, and you will see the following output.

Write Data to Database

Now let's insert one more record into the database and then read all the records using the following code.

Let's run the above code and you will see the following output.

For more information about file handling, visit https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection

All the examples related to the database operations are available in the DatabaseOperations.cs file of the source code. Download the source code and try out all the examples for better understanding.

Got any VB.NET Question?

logo rip

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

Chapter 25 Databases with VB.NET

  • the nature of simple databases and the SQL language;
  • how SQL can be used with VB;
  • the VB classes which provide database access.

Introduction

  • as one of its tasks, the VB program needs some form of data store, and a database is most suitable.
  • the programmer wishes to take advantage of the power of VB and its classes to provide a more powerful interface to a database than a conventional stand- alone database product allows.

The elements of a database

The Visuals ABC Co 65.2
RadioStar ABC Co 22.7
Mike Parr Media Ltd 3.5
The Objects Class UK 12.6
Assignment 182 Media Ltd 34.6
The Trees United Co 3.72
  • The table is made up of a collection of similar records . In the above, we have represented each record as a row.
  • A record is made up of a number of fields . In the above, we have three fields, named Artist , Company , and Sales . Effectively, a field name is a column name.
  • The assumption has been made that artist names are unique, so we used this as the primary key. However, if the table contained for example student names in a college, we would have to introduce a unique student I.D number. For the above table, we set up the Artist field as the primary key when we created it, and this prohibits us from introducing other artists with the same name.
ABC Co London
Media Ltd Chicago
Class UK Madrid
United Co London

The SQL language - introduction

The select statement.

  • select Artist from Artists This returns an item from every Artist field in the Artists table (i.e. the complete Artist column).
  • select * from Artists This returns the items from every field in the Artists table. Effectively, it returns the complete table.
  • select * from Artists where Company = 'Media Ltd' returns only the records from Artists where the company is Media Ltd . We enclose strings in single quotes. Strings are case- sensitive, so use capitals where they were used in the original database.
  • select * from Artists where Sales > 20 Returns only those records with sales above 20. Note that there are no quotes around numbers. The available operators are > = = where <> means 'not equals'.
  • select * from Companies where Company = 'ABC Co' This returns the single record from Companies , involving ABC Co
  • select * from Artists order by Sales asc The order by item can be added to any selection. We can use asc or desc to specify ascending or descending order. The above statement puts the records in ascending order of sales.

The insert statement

The delete statement, the update statement, the vb database classes, the oledbconnection class, the oledbdataadapter class, commandtext, executenonquery, updatecommand, deletecommand, insertcommand, the datatable class.

  • rows and columns are numbered from 0 upwards.
  • The data table holds instances of the class Object , so when we extract an item, we convert it to the appropriate type. (For example we convert an item to a String if it is to be displayed in a text box.)

The DataGrid class

The oledbcommandbuilder class, creating a database program.

  • Create a new project. Wait until the blank form appears.
  • View | Server Explorer
  • Right-click on Data Connections , then choose Add Connection...
  • A Data Link Properties windows appears. Select Provider at the top, then select the appropriate provider for your database. (For Microsoft Access databases, choose Microsoft Jet 4.0) , then click Next
  • The Connection tab appears. At step 1 , browse to your database file, and select it.
  • Delete Admin from the User name text box.
  • Move to the Server Explorer window, and left-click on Data Connections . The file name that you selected should appear. (Double- clicking on the name allows you to examine the database.)
  • Now we add the data connection to the program. Click on the name of your database file in the Server Explorer window, and drag it onto your form. An object named OleDbConnection1 appears in the system tray.
  • close the Server Explorer window, and view the toolbox. Instead of selecting Windows Forms, choose Data
  • Place an OleDbDataAdapter on the form. (Assuming you have an Access database). A wizard opens up.
  • The wizard can create SQL commands for you. We will write our own, but the wizard steps must be followed. Click Next
  • Ensure that your data connection is selected in the drop-down list. Click Next .
  • Ensure the Use SQL Statements is selected, and click Next .
  • On the Generate the SQL statements pane, choose Query Builder... An Add Table window appears.
  • Select one of your data tables (any one will do) and click Add , then Close .
  • A list of all the fields of the chosen table appears. Put a tick against All Columns . Click OK
  • An SQL Select query is shown. Click Finish .

Example - database manipulation

  • The user-interface is not error-proofed. For example, an insert can be attempted even if all the fields are empty. The omission is intentional, to avoid obscuring the database code.
  • To create the program, follow the setting-up process for the data connection and data adapter. Then create the GUI and enter the code. The three text boxes have been renamed to ArtistBox , CompanyBox , and SalesBox .
  • Every time we create an SQL command, we display it in SQLLabel at the bottom of the form, before executing the command. The reason is that, although the VB compiler makes detailed checks on your VB coding, it does not check the contents of strings, and knows nothing about SQL. Thus, SQL statement errors are only detected at run-time, and it is useful to have a display of the SQL code. Many errors are simple mistakes with single quotes.
  • It is essential to use exception-handling. In this program, we display the Message property, which provides an explanation of any errors.
  • When deleting, inserting, and updating, we need to open and close the connection. We place the Close call within the Finally of the exception-handling code, so that it is performed whatever happens within the Try .

Example - the data grid

  • To create the program, follow the setting-up instructions for the data connection and data adapter.
  • Place a data grid on the form. It can be found in the toolbox.
  • The data table is declared as a Private variable, because it is shared by both methods.
  • The DataSource property of the grid is used to bind table . This means that when table changes (via the Fill method) then the table is re- displayed in the grid automatically
  • To update a record, type in the new values.
  • To insert a new record, type it at the bottom of the grid, alongside the * .
  • To delete a record, click the button at the left of the record. This highlights all the fields. Press the delete key on the keyboard to delete it.
  • To resize the columns, place the mouse between the buttons at the top of the columns, and drag.
  • To sort the records based on a particular column, click the button at the top of a column. Clicking again changes from ascending order to descending order.
  • The program does not check for errors after each modification of the data grid. For example, if the user enters a company that does not already exist in the Companies table, then this error will only come to light when we click Save . Thus, exception-handling is essential at the saving stage.

Programming principles

Programming pitfalls.

  • It is very easy to make errors when creating SQL strings. Take care with single-quotes, and, when debugging, display the SQL command.
  • When executing queries with Fill , you do not need to use Open and Close . In every other case, they are needed.

Grammar spot

  • The Rows property of a data table takes two bracketed integer expressions, and returns an Object . We convert it to our required type, as in: Dim n As Integer = CInt(table.Rows(3) (4))

New language elements

New ide facilities.

  • We have used the ADO.NET classes to access databases.
  • A range of databases can be accessed, not only those created by Microsoft Access.
  • The basic approach is to create and execute strings containing SQL statements.

VB.NET SQL Examples for Querying Databases Efficiently

4

Your changes have been saved

Email is sent

Email has already been sent

Please verify your email address.

You’ve reached your account maximum for followed topics.

How to Use Gemini in Google Sheets

These are my 10 favorite spotify playlists for background music, what are soulslike games the challenging genre explained.

VB.NET offers a streamlined approach to database operations, with a robust framework. Using its power, you can obtain relevant information quickly and with minimal effort.

Take a look at some practical examples that show how to use VB.NET to perform SQL queries, and see how you can ensure data retrieval is both effective and efficient.

Setting Up Your Local SQL Server

Start by setting up a SQL server to review everything step by step. In the examples below you will see a Windows environment, but if you are using a different operating system like Linux and have a different SQL server, don’t worry; the general logic will remain the same.

Due to its simplicity and zero configuration approach, SQLite is an excellent choice for beginners.

To set things up, create a new folder, then open a command prompt and navigate to it. Run the following command to create a new .NET project in which you can use the VB.NET language:

You now have a project called MyVBApp . Continue the setup by integrating the SQLite package into your VB.NET project using NuGet, a popular package manager for .NET. Run this command:

After you’ve added SQLite, you can set up a local database effortlessly.

You can find all the code for these examples in the project’s GitHub repository .

Download the InitializeDatabase.vb file from the project’s repository. This particular file will help you configure your database. As you can see in this file there are some users and users' countries. You can use this as a sample database.

The command you used to create the VB.NET project created a file named Program.vb . Open this file and update it as follows:

Run this program and you should see it create a file named mydatabase.db . This is the simple database that you will use in the following examples.

A database created with SQLite and visual basic

Establishing a Database Connection With SQL in VB.NET

Establishing a connection using SQLite in VB.NET is straightforward. Continue editing the Program.vb file and remove the existing contents of the Main subroutine. This file serves as the project's core.

You can define a connection to the database file, mydatabase.db, with this line of code:

Data Source specifies the database file name. If the file doesn't exist, SQLite will create a new database when it establishes a connection.

The next step is to use the SQLiteConnection class to create a connection instance. You should always use a Using block when working with database connections to avoid potential leaks or deadlocks:

The Using block ensures that the connection is automatically closed when it completes.

Your final Program.vb file should look something like this:

This code will connect to the mydatabase.db database and print a confirmation message when it succeeds. If an error occurs, it will print details to the console.

How to Fetch Data and Load It Into an Array

The SELECT SQL command is the main way of fetching data from an SQL database. If you have a table named Users in your database and you want to get the Name field from every record in that table, use SELECT like this:

You can pull data from the database and load it into an array by adding this query to the Program.vb file:

You’ll see a list of names on the console, corresponding to the contents of your database table:

List sqlite data in array with dotnet

This code loads the data into a List structure—which has a dynamic size—before converting it to an array on completion. This approach is very useful for situations where you do not know in advance the number of records you’ll retrieve.

How to Use INSERT to Add Data to a Database

You can use the INSERT INTO command to add new data to a database. For example, consider the Users table that has two columns named Name and Country .

The basic SQL query you can use to add a new user would be:

To add a new user to the database using this query, update the Program.vb file as follows:

This simple example uses string interpolation to build the query, but you should avoid this in production code since it’s vulnerable to SQL injection . The alternative is parameterized queries which make database operations safer and more efficient.

Parameterized queries use placeholders, instead of direct string concatenation, to add values to SQL queries. This approach will help you avoid many security threats:

Any Other Tips for Working With a Database From Within VB.Net

A server with images of computers and database

Database operations in VB.NET might initially seem daunting, but with a few guidelines, you can easily master the basics.

  • Use parametrized queries to guard against security vulnerabilities.
  • Always close your database connection when you’ve finished fetching or updating data.
  • Maintain your database to optimize its structure as your data model changes over time.
  • Don't forget to make backup copies in case of emergencies.

As with any technology, databases evolve. Software gets updated, new tools emerge, and we discover better ways of doing things. It's a good idea to stay informed and updated. Some tools act as intermediaries, like Entity Framework , making it easier to write database-related code.

How to Take Your VB.NET Journey Further

VB.NET, with its deep-rooted connection to the Microsoft ecosystem, is both robust and user-friendly. To truly grasp its power, start with the official documentation provided by Microsoft. From there, explore online courses, forums, and communities, where experienced developers share their knowledge and insights.

Remember, every expert was once a beginner. With consistent effort, curiosity, and the right resources, you'll soon find yourself navigating VB.NET with confidence and ease. As you progress, don't hesitate to experiment, ask questions, and—most importantly—enjoy the process of discovery.

  • Programming
  • Visual Basic Programming

vb net database assignment

Lesson 23 Creating a Database Application

23.1 creating simple database application.

Visual Basic provides the capability to effectively manage databases created with various database programs, including MS Access, Oracle, MySQL, and more. In this lesson, our focus is not on database file creation, but rather on accessing database files within the VB environment. To illustrate this concept, we will develop a straightforward database application that allows users to browse customer names. In the following example, we will create a simple database application which enables one to browse customers' names.  To create this application,  select the data control on the toolbox(as shown in Figure 23.1) and insert it into the new form. Place the data control somewhere at the bottom of the form. Name the data control as data_navigator . To be able to use the data control, we need to connect it to any database. We can create a database file using any database application but I suggest we use the database files that come with VB6. Let's select NWIND.MDB as our database file.

vb net database assignment

23.2 Connecting Data Control to Database

To connect the data control to this database, double-click the DatabaseName property in the Properties window and then click on the button with three dots on the right(as shown in Figure 23.2) to open a file selection dialog as shown in Figure 23.3. From the dialog, search the folders of your hard drive to locate the database file NWIND.MDB. It is usually placed under Microsoft Visual Studio\VB98\ folder, Select the aforementioned file and now your data control is connected to this database file.

vb net database assignment

The next step is to double-click on the RecordSource property to select the customers table from the database file NWIND.MDB, as shown in Figure 23.4. You can also change the caption of the data control to anything, we use Click to browse Customers. After that, we will place a label and change its caption to Customer Name. In addition, insert another label and name it as cus_name and leave the label empty as customers' names will appear here when we click the arrows on the data control. We need to bind this label to the data control for the application to work. To do this, open the label's DataSource and select data_navigator that will appear automatically. One more thing that we need to do is to bind the label to the correct field so that data in this field will appear on this label. To do this, open the DataField property and select ContactName, as shown in Figure 23.5.

vb net database assignment

Now, press F5 and run the program. You should be able to browse all the customers' names by clicking the arrows on the data control, as hown in Figure 23.7.

The Design Interface.

vb net database assignment

You can also add other fields using exactly the same method. For example, you can add title, company, adress, City, postcode ,telephone number and more to the database browser. Besides, you can design a more professional interface, as shown in Figure 23.8.

vb net database assignment

Figure 23.8

Copyright©2008 Dr.Liew Voon Kiong. All rights reserved | Contact | Privacy Policy

How to Connect Access Database in VB.Net

Database access in vb.net.

Applications talk to a database in two ways: first, to get the data stored there and show it in a way that’s easy to understand, and second, to update the database by adding , Updating , or removing data .

Microsoft ActiveX Data Objects.Net (ADO.Net) is a model that is part of the .Net framework .

Data Provider

The following four things make up the ADO.Net data provider :

Description
1. This component is used to set up a connection with a data source.
2. A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data source.
3. Data reader is used to retrieve data from a data source in a read-only and forward-only mode.
4. This is integral to the working of ADO.Net since data is transferred to and from a database through a data adapter. It retrieves data from a database into a dataset and updates the database. When changes are made to the dataset, the changes in the database are actually done by the data adapter.

How to Connect Access Database in VB.net

Time needed:  20 minutes

In this final step, we will start adding functionality to our vb.net program by adding some functional codes.

Code To Connect Access Database in VB.Net

Double the “Form1” and add the following code under “Public Class Form1” .

Inside OledbConnection , we pasted the connection string we copied from the “Step 11” instructions.

Test the Connection of Access database in VB.Net

To test the connection between the MS access database and VB.Net , Double click form1 a nd add the following code under “Form1_Load” events.

How to Load Record from Access Database to Datagridview In VB.Net

In this section, we will learn how to load a record from the Access database to Datagridview using vb.net . To start with, double-click the “ Load record” button and add the following code.

After adding the code, you may press F5 or click the Start debugging button to test the code. The output should look like as shown below.

Save Record in Access Database using VB.net

Updating of records from access database in vb.net.

In this section, we will learn how to update records from an access database using vb.net . In order for us to proceed in updating the record , we will add first a code to pass value from datagridview to textboxes.

So here’s the following code.

Only the Query is different.

Deleting of Records from Access Database In VB.Net

After this process, you can now run the program to test if all the codes in this tutorial are working well.

Watch the full video tutorial about How to Connect to an Access Database in VB.NET until the end to see the bonus techniques and apply them to your project.

Download the vb.net project full Source code Below.

Frequently Asked Questions

The data provider is used to connect to a database. Executing commands and retrieving data, storing it in a Dataset, reading the retrieved data, and updating the database.

This is integral to the working of ADO.Net since data is transferred to and from a database through a data adapter. It retrieves data from a database into a dataset and updates the database. When changes are made to the dataset, the changes in the database are actually done by the data adapter.

OleDbConnection is designed for connecting to a wide range of databases, like Microsoft Access and Oracle.

If you have any questions or suggestions about how to connect to access the database in vb.net, please leave a comment below.

Other Articles Readers might read:

6 thoughts on “how to connect access database in vb.net”.

thank you very much

zoom class?

wHAT IS & txtitemname.Text & .. YOU DIDNT DECLARED AMP.

and I am very thankful to him

Thank you very much 👍

Please help

Leave a Comment Cancel reply

CodeAvail

25+ Latest VB.Net Project Topics For Students [2024]

vb.net project topics

VB.Net, a versatile programming language, holds significant relevance in today’s tech-driven world. It is a powerful tool for developing various applications, from simple utilities to complex enterprise systems. Its user-friendly syntax and extensive framework make it an ideal choice for students looking to delve into the world of software development.

When it comes to learning VB.Net, practical application through project-based learning is invaluable. By working on projects, students can apply theoretical knowledge to real-world scenarios, thereby reinforcing their understanding and skills. 

Additionally, projects provide a hands-on learning experience that fosters creativity, problem-solving abilities, and critical thinking—all essential qualities for aspiring programmers.

In this blog, we aim to showcase the benefits of using project topics in VB.Net for students. We will explore a diverse range of VB.Net project topics suited for various skill levels, from beginners to advanced learners. Join us as we embark on this journey of learning and discovery in the world of VB.Net projects.

What is a VB.NET Project?

Table of Contents

A VB.NET project is a software development endeavor undertaken using the Visual Basic.NET programming language. It involves the creation of applications, utilities, or systems using the features and capabilities provided by VB.NET. 

Projects can range from simple desktop applications to more complex web applications or enterprise-level software solutions. VB.NET projects typically involve designing, coding, testing, and debugging software components to achieve specific functionalities or address particular needs. 

These projects serve as practical learning experiences for students and professionals, allowing them to apply VB.NET concepts and techniques in real-world scenarios.

Example of VB.NET Project

One example of a VB.NET project could be a simple inventory management system for a small business. This project would involve creating a desktop application using Visual Basic.NET that allows users to track inventory levels, add new items, remove items, and generate reports.

The project would include features such as a user-friendly interface for inputting and editing inventory data, validation to ensure data accuracy, and the ability to generate reports on inventory levels, sales trends, and stock shortages.

Additionally, the project might incorporate database integration to store and retrieve inventory data and functionality for exporting reports to various file formats such as Excel or PDF.

Overall, this VB.NET project provides a practical example of how the language can be used to develop functional business applications to streamline operations and improve efficiency.

Trending VB.Net Project Topics For Beginners to Advanced Level

vb net database assignment

Here’s a list of the best VB.NET project topics suitable for beginners to advanced-level developers:

Beginners Developers

1. Simple Calculator Application

Create a basic calculator application in VB.Net that performs arithmetic operations like addition, subtraction, multiplication, and division. This project will help beginners grasp fundamental concepts such as user input, event handling, and basic arithmetic operations in VB.Net.

2. To-Do List Manager

Develop a to-do list manager application that allows users to add, edit, delete, and mark tasks as completed. This project will introduce beginners to concepts such as data manipulation, user interface design, and handling user interactions using VB.Net.

3. Temperature Converter

Design a temperature converter application that converts temperatures between Celsius, Fahrenheit, and Kelvin scales. This project will familiarize beginners with variables, data types, conditional statements, and mathematical operations in VB.Net.

4. Student Grade Calculator

Build a student grade calculator application that calculates average grades, determines letter grades, and provides feedback based on input scores. This project will involve implementing loops, arrays, and conditional statements to handle multiple student records in VB.Net.

5. Simple Text Editor

Create a basic text editor application with features like text entry, editing, saving, and opening files. This project will introduce beginners to file handling, text manipulation, and basic GUI (Graphical User Interface) design using VB.Net.

6. Currency Converter  

Develop a currency converter application that converts currencies between different countries based on real-time exchange rates. This project will involve retrieving data from external APIs, parsing JSON/XML data, and displaying results in VB.Net.

7. BMI (Body Mass Index) Calculator

Design a BMI calculator application that calculates a person’s BMI based on their height and weight inputs. This project will teach beginners about mathematical formulas, input validation, and displaying results in VB.Net.

8. Quiz Application

Create a simple quiz application with multiple-choice questions on various topics. This project will involve designing a user interface for displaying questions, handling user responses, scoring, and providing feedback using VB.Net.

9. Library Management System

Develop a basic library management system that allows users to add, edit, delete, and search for books in a library database. This project will introduce beginners to database management, SQL queries, and CRUD (Create, Read, Update, Delete) operations in VB.Net.

Intermediate Devlopers

10. Inventory Management System

Design an inventory management system for a small business, allowing users to track stock levels, manage suppliers, generate reports, and automate reordering processes. This project involves database integration and advanced GUI design.

11. Expense Tracker

Develop an expense-tracking application that helps users record, categorize, and analyze their expenses over time. This project involves database management, data visualization, and advanced user input validation.

12. Banking System Simulation

Create a banking system simulation with features like account creation, funds transfer, balance inquiries, and transaction history. This project involves implementing object-oriented programming principles, encryption techniques, and robust error handling.

13. Hospital Management System

Build a hospital management system for managing patient records, scheduling appointments, tracking medical staff, and generating medical reports. This project involves database design, user authentication, and role-based access control.

14. Online Bookstore

Develop an online bookstore application where users can browse, search, purchase, and review books. This project involves web development using ASP.NET, database integration for managing book inventory and orders, and secure payment processing.

15. Employee Attendance System

Design an employee attendance tracking system that records employee clock-ins, clock-outs, absences, and overtime hours. This project involves real-time data processing, user authentication, and data visualization.

16. E-commerce Website

Create an e-commerce website where users can browse products, add items to their cart, checkout, and manage their orders. This project involves web development using ASP.NET MVC, database management, and integration with payment gateways.

17. Customer Relationship Management (CRM) System

Develop a CRM system for businesses to manage customer interactions, track leads, analyze sales data, and automate marketing campaigns. This project involves database design, data analytics, and integration with email marketing tools.

18. Online Auction System

Build an online auction platform where users can bid on items, monitor auctions, and manage their bids. This project involves real-time communication, bidding algorithms, secure payment processing, and user feedback mechanisms.

Advanced Developers

19. Social Media Analytics Dashboard

Develop a comprehensive analytics dashboard for social media platforms, allowing users to track engagement metrics, analyze trends, and generate reports. This project involves data aggregation from APIs, data visualization using advanced charting libraries, and predictive analytics algorithms.

20. Machine Learning-Based Stock Prediction

Create a stock prediction application using machine learning algorithms to forecast stock prices based on historical data. This project involves data preprocessing, feature engineering, model training, and deployment using VB.Net and ML.NET library.

21. Virtual Reality Simulation

Design a virtual reality simulation application for training purposes, such as flight simulation or medical procedures. This project involves integrating VR hardware, developing immersive environments, and implementing interactive simulations using VB.Net and Unity3D.

22. Automated Trading System

Build an automated trading system that executes buy/sell orders in financial markets based on predefined trading strategies. This project involves real-time market data processing, algorithmic trading strategies, and risk management techniques implemented in VB.Net.

23. Natural Language Processing (NLP) Chatbot

Develop a conversational chatbot capable of understanding and responding to natural language queries. This project involves training NLP models, integrating with language processing APIs, and implementing dialogue management logic using VB.Net and libraries like NLTK or spaCy.

24. Smart Home Automation System

Design a smart home automation system that enables users to control various home devices remotely through a centralized application. This project involves IoT integration, sensor data processing, and implementing automation rules using VB.Net and Arduino/Raspberry Pi.

25. Computer Vision-Based Object Recognition

Create an object recognition application using computer vision algorithms to detect and classify objects in images or videos. This project involves deep learning models, image processing techniques, and integration with the OpenCV library using VB.Net.

26. Blockchain-Based Voting System

Develop a secure and transparent voting system using blockchain technology to ensure the integrity and immutability of voting records. This project involves implementing smart contracts, distributed ledger technology, and cryptographic techniques in VB.Net and the Ethereum platform.

27. Healthcare Data Analysis Platform

Build a healthcare data analysis platform for medical professionals to analyze patient records, diagnose diseases, and predict treatment outcomes. This project involves data integration from healthcare databases, machine learning algorithms for predictive analytics, and HIPAA-compliant data management using VB.Net and Python libraries.

These project ideas should provide a good starting point for beginners and also challenge more advanced developers to explore deeper functionality and implementation details.

Advantages of using VB.NET Project Topics for Students

There are several advantages to using VB.NET project topics for students:

  • User-Friendly Syntax: VB.NET offers a simple and intuitive syntax, making it easier for students to learn and understand programming concepts.
  • Extensive Framework: Students can leverage the extensive .NET framework provided by VB.NET, allowing for rapid application development with built-in functionalities.
  • Abundance of Resources: VB.NET has a vast community and ample online resources, including tutorials, forums, and documentation, providing valuable support for students during their learning journey.
  • Seamless Integration: VB.NET seamlessly integrates with other Microsoft technologies like SQL Server, Azure, and Office applications, offering students a holistic understanding of software development.
  • Career Opportunities: Proficiency in VB.NET opens doors to a wide range of career opportunities in software development, particularly in industries where Microsoft technologies are prevalent.

How to Make Setup of VB.NET Project

Creating a setup for a VB.NET project involves packaging your application along with any required dependencies and creating an installer that users can run to install your application on their systems. Here’s a step-by-step guide on how to create a setup for a VB.NET project using Visual Studio:

  • Open your VB.NET project in Visual Studio.
  • Navigate to the “Build” menu and select “Publish <YourProjectName>”.
  • In the Publish Wizard, choose the publishing location, such as a folder, FTP server, or Azure App Service.
  • Configure publishing options like deployment mode and updates.
  • Click “Finish” to generate the deployment package.
  • Distribute the generated setup files to users for installation.
  • Optionally, create an installer using third-party tools like Inno Setup or WiX Toolset for a more customizable installation process.

By following these steps, you can create a setup for your VB.NET project and distribute it to users for installation on their systems.

Tips for Successful Implementation

Implementing VB.NET projects successfully requires careful planning, adherence to best practices, and effective project management. Here are some tips to ensure successful implementation:

Plan Thoroughly

Clearly define project requirements, objectives, and scope before starting development.

Follow Best Practices

Adhere to coding standards, use meaningful variable names, and organize your code logically.

Use Version Control

Utilize version control systems like Git to manage code changes and collaborate effectively.

Test Rigorously

Conduct thorough testing at each stage of development to catch bugs early and ensure software reliability.

Document Extensively

Document code, design decisions, and project processes to facilitate maintenance and future enhancements.

Seek Feedback

Solicit feedback from stakeholders and end-users throughout the development process to ensure alignment with requirements and expectations.

By following these tips, you can increase the likelihood of success in implementing VB.NET projects delivering high-quality software solutions that meet stakeholders’ requirements and expectations.

Final Thoughts

VB.NET project topics offer an invaluable opportunity for students to enhance their programming skills and explore the diverse applications of the Visual Basic.NET language. 

From beginner-level projects focusing on fundamental concepts to advanced endeavors incorporating cutting-edge technologies, the realm of VB.NET projects is vast and enriching. By undertaking these projects, students not only solidify their understanding of programming principles but also develop problem-solving abilities and creativity. 

Whether it’s building simple utilities or complex enterprise systems, the journey of exploring VB.NET project topics is both educational and rewarding, paving the way for future success in software development endeavors.

1. How do I choose the right VB.Net project topic?

Consider your interests, skill level, and career goals when selecting a project topic. Choose something that challenges you but is also achievable within your capabilities.

2. Can I use VB.NET for web development?

Yes, VB.NET can be used for web development through ASP.NET, a web application framework developed by Microsoft. ASP.NET allows developers to build dynamic web applications using VB.NET for server-side programming, HTML/CSS for front-end design, and SQL Server for database integration.

3. How can I get started with VB.NET projects if I’m new to programming?

To begin with VB.NET projects, it’s advisable to start with simple projects like a calculator or to-do list manager. Utilize online resources such as tutorials, forums, and documentation to learn the basics of VB.NET programming. Practice regularly and gradually tackle more complex projects as you gain confidence and proficiency in the language.

Related Posts

Science Fair Project Ideas For 6th Graders

Science Fair Project Ideas For 6th Graders

When it comes to Science Fair Project Ideas For 6th Graders, the possibilities are endless! These projects not only help students develop essential skills, such…

Java Project Ideas For Beginners

Java Project Ideas for Beginners

Java is one of the most popular programming languages. It is used for many applications, from laptops to data centers, gaming consoles, scientific supercomputers, and…

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

124aris/VB.NET-Assignment-2

Folders and files.

NameName
2 Commits
  • Visual Basic .NET 100.0%

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Open SQL Server database by using SQL Server .NET Data Provider with Visual Basic .NET

  • 3 contributors

This article provides information about how to open SQL Server databases by using SQL Server .NET Data Provider with Visual Basic .NET.

Original product version:   Visual Basic .NET Original KB number:   308656

This article describes how you can use ADO.NET to open a SQL Server database by using the SQL Server .NET data provider. ADO.NET gathers all of the classes that are required for data handling. The System.Data.SqlClient namespace describes a collection of classes that are used to programmatically access a SQL Server data source. You can access ADO classes through the System.Data.OleDb namespace to provide support for OLE DB databases.

In this article, connections are set up both programmatically and using the Visual Studio .NET Server Explorer. The code samples in this article use the SqlConnection , SqlCommand , and SqlDataReader ADO.NET objects.

Requirements

The following list outlines the required hardware, software, network infrastructure, and service packs that you need:

  • Microsoft SQL Server
  • Visual Basic .NET

SQL Server and Visual Basic .NET must be installed and running on the same computer. In addition, the user must be able to use Windows Integrated Security to connect to SQL Server.

This article assumes that you're familiar with the following topics:

  • ADO.NET concepts
  • SQL Server concepts and Transact-SQL (T-SQL) syntax
  • Northwind sample database

Create Visual Basic .NET Windows application

Start Visual Studio .NET, and create a new Visual Basic Windows Application project named SQLDataAccess .

Open Form1. In the first line of Form1.vb , add a reference to the ADO.NET namespace as follows:

From the Windows Start menu, point to Programs , point to Microsoft SQL Server, and then click SQL Server Service Manager to ensure that the SQL Server service is running on your computer.

Set the Server property to the name of your computer, and then set the Services property to MSSQLServer .

If the service isn't running, click Start .

Close the SQL Server Service Manager dialog box.

Create ADO.NET objects

Modify the Form1 class as follows:

The SqlConnection object establishes a database connection, the SqlCommand object runs a query against the database, and the SqlDataReader object retrieves the results of the query.

Use the SqlConnection object to open SQL Server connection

To set up the connection string of the SqlConnection object, add the following code to the Form1_Load event procedure:

To set up the Command object, which contains the SQL query, add the following code to the Form1_Load event procedure:

SqlConnection uses your Windows logon details to connect to the Northwind database on your computer.

Use the SqlDataReader object to retrieve data from SQL Server

Add the following code to the Form1_Load event procedure:

When the myCmd.ExecuteReader method is executed, SqlCommand retrieves two fields from the Employees table and creates a SqlDataReader object.

To display the query results, add the following code to the Form1_Load event procedure:

The myReader.Read method returns a boolean value, which indicates whether there are more records to be read. The results of the SQL query are displayed in a message box.

To close the SqlDataReader and SqlConnection objects, add the following code to the Form1_Load event procedure:

Save and run the project.

View database in Server Explorer

  • On the View menu, click Server Explorer.
  • Right-click Data Connections , and then click Add connection .
  • In the Data Link Properties dialog box, click localhost in the Select or enter a server name box.
  • Click Windows NT Integrated Security to log on to the server.
  • Click Select the database on the server , and then select Northwind database from the list.
  • Click Test Connection to validate the connection, and then click OK .
  • In the Server Explorer, click to expand the Data Connections tree so that the Employees table node expands. The properties of individual fields appear in the Properties window.

Use Server Explorer to open SQL Server connection

View Form1 in Design view.

Drag the FirstName and LastName database fields from Employees table in Server Explorer, and drop these fields onto Form1. A SqlConnection and SqlDataAdapter object are created on the form.

From the View menu, click Toolbox .

On the Data tab, drag a DataSet object (DataSet1), and drop it onto the form.

In the Add Dataset dialog box, click Untyped dataset , and then click OK .

Insert a line of code before the DataReader and Connection objects are closed in the Form1_Load event procedure. The end of the procedure should appear as follows:

On the Window Forms tab of the toolbox, drag a DataGrid control, and drop it onto Form1.

To bind the DataGrid to the DataSet object that you created earlier, add the following code to the Form1_Load event procedure before the myReader.close() line of code:

For more information about using ADO.NET, refer to the Data section of the Visual Basic topic in the Visual Studio .NET Help documentation.

Was this page helpful?

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Creating an array of student names and scores in Visual Basic that updates a list box with the information

I am working on a project that has multiple forms. The main form has a listBox that displays the contents of a tab delimited text file. The text file looks like this:

Bowser, William C 84 98 77 83 75 92 Smithson, Anne K 76 87 65 Brewer, Juliette 23 Oblonski, Walter H 88 97 86 75 93 98 Smith, John D 86 75 84 93 91 78 Katinga, Raphael P 56 87 44 32 22 Robertson, Gerald T 67 78 87 93 87 75 Smith, John B 89 67 75 84 92 83

The assignment is as follows:

StudentScores Develop an application that reads in student names (limited to 20 students) and scores (up to 6 per student) from a tab delimited file, StudentScores.txt (in Student Files). The application shall allow the user to add students to the student set, add and change scores for a student in the student set, delete a student and the student’s scores from the student set, and save the student set back to the StudentScores.txt file.

I am not having any luck getting it to correctly add a new student & scores or save the current "updated" information. I think I am not using my arrays correctly. below is my code for the main form (frmStudentScores) and a second form (frmAddNewStudent)

My frmStudentScores code:

The code for form frmAddNewStudent (used to add a new student) is:

Also I have a Module with the name and scores arrays in it:

Cœur's user avatar

  • 1 Parallel arrays are a horrible choice for this type of task –  OneFineDay Commented Dec 11, 2014 at 5:06
  • Thats what I was told but the assignment specifically ask for parallel arrays. How would you advise me to do it if I were not using the parallel arrays? I am more interested in making it work than I am about using parallel arrays. –  Chip Datamaker Commented Dec 11, 2014 at 5:09
  • 1 Ask your teacher if this would be acceptable in the work place, the answer would be no. There is a place for arrays and this is not it. Some day schools are going to have to step up and change there stupid curriculum. –  OneFineDay Commented Dec 11, 2014 at 5:11
  • Arrays need to be ReDim before adding, all arrays must be dimension-ed the same if they are to be used by the same index. –  OneFineDay Commented Dec 11, 2014 at 5:15
  • Do you think a Jagged Array would work better here? –  Chip Datamaker Commented Dec 11, 2014 at 5:20

Example of a custom class:

Get a students average grade(lambda expression):

OneFineDay's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged vb.net or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Why didn't Air Force Ones have camouflage?
  • Replacing jockey wheels on Shimano Deore rear derailleur
  • What was the typical amount of disk storage for a mainframe installation in the 1980s?
  • Riemannian metric for which arbitary path becomes a geodesic
  • Can I use Cat 6A to create a USB B 3.0 Superspeed?
  • Does the average income in the US drop by $9,500 if you exclude the ten richest Americans?
  • Nausea during high altitude cycling climbs
  • Is "in spirit and truth" a hendiadys describing the worshipper who is born again?
  • Deleting all files but some on Mac in Terminal
  • "It never works" vs "It better work"
  • do-release-upgrade from 22.04 LTS to 24.04 LTS still no update available
  • What`s this? (Found among circulating tumor cells)
  • Stained passport am I screwed
  • Can reinforcement learning rewards be a combination of current and new state?
  • Why is it spelled "dummy" and not "dumby?"
  • Why is LiCl a hypovalent covalent molecule?
  • Issue with the roots of the Equation of Time
  • Can I replace the 'axiom schema of specification' in ZF by 'every subclass is a set'?
  • What should I consider when hiring a graphic designer to digitize my scientific plots?
  • Did the Turkish defense industry ever receive any significant foreign investment from any other OECD country?
  • Why does the church of latter day saints not recognize the obvious sin of the angel Moroni according to the account of Joseph Smith's own words?
  • Is a stable quantifier-free language really possible?
  • Why is the soil in my yard moist?
  • How do I learn more about rocketry?

vb net database assignment

VB.Net Programming Tutorial

  • VB.Net Basic Tutorial
  • VB.Net - Home

VB.Net - Overview

Vb.net - environment setup, vb.net - program structure, vb.net - basic syntax, vb.net - data types, vb.net - variables.

  • VB.Net - Constants

VB.Net - Modifiers

Vb.net - statements, vb.net - directives, vb.net - operators, vb.net - decision making, vb.net - loops, vb.net - strings, vb.net - date & time, vb.net - arrays, vb.net - collections, vb.net - functions.

  • VB.Net - Subs

VB.Net - Classes & Objects

Vb.net - exception handling, vb.net - file handling, vb.net - basic controls, vb.net - dialog boxes.

  • VB.Net - Advanced Forms

VB.Net - Event Handling

  • VB.Net Advanced Tutorial

VB.Net - Regular Expressions

Vb.net - database access, vb.net - excel sheet, vb.net - send email, vb.net - xml processing, vb.net - web programming.

  • VB.Net Useful Resources

VB.Net - Quick Guide

  • VB.Net - Useful Resources
  • VB.Net - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented on the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not backwards-compatible with VB6, and any code written in the old version does not compile under VB.NET.

Like all other .NET languages, VB.NET has complete support for object-oriented concepts. Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String, Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherits from the base class Object.

VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access to all the libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-source alternative to .NET, not only under Windows, but even Linux or Mac OSX.

The following reasons make VB.Net a widely used professional language −

Modern, general purpose.

Object oriented.

Component oriented.

Easy to learn.

Structured language.

It produces efficient programs.

It can be compiled on a variety of computer platforms.

Part of .Net Framework.

Strong Programming Features VB.Net

VB.Net has numerous strong programming features that make it endearing to multitude of programmers worldwide. Let us mention some of these features −

Boolean Conditions

Automatic Garbage Collection

Standard Library

Assembly Versioning

Properties and Events

Delegates and Events Management

Easy-to-use Generics

Conditional Compilation

Simple Multithreading

In this chapter, we will discuss the tools available for creating VB.Net applications.

We have already mentioned that VB.Net is part of .Net framework and used for writing .Net applications. Therefore before discussing the available tools for running a VB.Net program, let us understand how VB.Net relates to the .Net framework.

The .Net Framework

The .Net framework is a revolutionary platform that helps you to write the following types of applications −

Windows applications

Web applications

Web services

The .Net framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages: Visual Basic, C#, C++, Jscript, and COBOL, etc.

All these languages can access the framework as well as communicate with each other.

The .Net framework consists of an enormous library of codes used by the client languages like VB.Net. These languages use object-oriented methodology.

Following are some of the components of the .Net framework −

Common Language Runtime (CLR)

The .Net Framework Class Library

Common Language Specification

Common Type System

Metadata and Assemblies

Windows Forms

ASP.Net and ASP.Net AJAX

Windows Workflow Foundation (WF)

Windows Presentation Foundation

Windows Communication Foundation (WCF)

For the jobs each of these components perform, please see ASP.Net - Introduction , and for details of each component, please consult Microsoft's documentation.

Integrated Development Environment (IDE) For VB.Net

Microsoft provides the following development tools for VB.Net programming −

Visual Studio 2010 (VS)

Visual Basic 2010 Express (VBE)

Visual Web Developer

The last two are free. Using these tools, you can write all kinds of VB.Net programs from simple command-line applications to more complex applications. Visual Basic Express and Visual Web Developer Express edition are trimmed down versions of Visual Studio and has the same look and feel. They retain most features of Visual Studio. In this tutorial, we have used Visual Basic 2010 Express and Visual Web Developer (for the web programming chapter).

You can download it from here . It gets automatically installed in your machine. Please note that you need an active internet connection for installing the express edition.

Writing VB.Net Programs on Linux or Mac OS

Although the.NET Framework runs on the Windows operating system, there are some alternative versions that work on other operating systems. Mono is an open-source version of the .NET Framework which includes a Visual Basic compiler and runs on several operating systems, including various flavors of Linux and Mac OS. The most recent version is VB 2012.

The stated purpose of Mono is not only to be able to run Microsoft .NET applications cross-platform, but also to bring better development tools to Linux developers. Mono can be run on many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris and UNIX.

Before we study basic building blocks of the VB.Net programming language, let us look a bare minimum VB.Net program structure so that we can take it as a reference in upcoming chapters.

VB.Net Hello World Example

A VB.Net program basically consists of the following parts −

Namespace declaration

A class or module

One or more procedures

The Main procedure

Statements & Expressions

Let us look at a simple code that would print the words "Hello World" −

When the above code is compiled and executed, it produces the following result −

Let us look various parts of the above program −

The first line of the program Imports System is used to include the System namespace in the program.

The next line has a Module declaration, the module Module1 . VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses.

Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be any of the following −

RemoveHandler

The next line( 'This program) will be ignored by the compiler and it has been put to add additional comments in the program.

The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed.

The Main procedure specifies its behavior with the statement

Console.WriteLine("Hello World") WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.

The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET.

Compile & Execute VB.Net Program

If you are using Visual Studio.Net IDE, take the following steps −

Start Visual Studio.

On the menu bar, choose File → New → Project.

Choose Visual Basic from templates

Choose Console Application.

Specify a name and location for your project using the Browse button, and then choose the OK button.

The new project appears in Solution Explorer.

Write code in the Code Editor.

Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World.

You can compile a VB.Net program by using the command line instead of the Visual Studio IDE −

Open a text editor and add the above mentioned code.

Save the file as helloworld.vb

Open the command prompt tool and go to the directory where you saved the file.

Type vbc helloworld.vb and press enter to compile your code.

If there are no errors in your code the command prompt will take you to the next line and would generate helloworld.exe executable file.

Next, type helloworld to execute your program.

You will be able to see "Hello World" printed on the screen.

VB.Net is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.

When we consider a VB.Net program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean.

Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class.

Class − A class can be defined as a template/blueprint that describes the behaviors/states that objects of its type support.

Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

A Rectangle Class in VB.Net

For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and displaying details.

Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the basis of our observations in it −

In previous chapter, we created a Visual Basic module that held the code. Sub Main indicates the entry point of VB.Net program. Here, we are using Class that contains both code and data. You use classes to create objects. For example, in the code, r is a Rectangle object.

An object is an instance of a class −

A class may have members that can be accessible from outside class, if so specified. Data members are called fields and procedure members are called methods.

Shared methods or static methods can be invoked without creating an object of the class. Instance methods are invoked through an object of the class −

Identifiers

An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in VB.Net are as follows −

A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.

It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.

It should not be a reserved keyword.

VB.Net Keywords

The following table lists the VB.Net reserved keywords −

AddHandler AddressOf Alias And AndAlso As Boolean
ByRef Byte ByVal Call Case Catch CBool
CByte CChar CDate CDec CDbl Char CInt
Class CLng CObj Const Continue CSByte CShort
CSng CStr CType CUInt CULng CUShort Date
Decimal Declare Default Delegate Dim DirectCast Do
Double Each Else ElseIf End End If Enum
Erase Error Event Exit False Finally For
Friend Function Get GetType GetXML Namespace Global GoTo
Handles If Implements Imports In Inherits Integer
Interface Is IsNot Let Lib Like Long
Loop Me Mod Module MustInherit MustOverride MyBase
MyClass Namespace Narrowing New Next Not Nothing
Not Inheritable Not Overridable Object Of On Operator Option
Optional Or OrElse Overloads Overridable Overrides ParamArray
Partial Private Property Protected Public RaiseEvent ReadOnly
ReDim REM Remove Handler Resume Return SByte Select
Set Shadows Shared Short Single Static Step
Stop String Structure Sub SyncLock Then Throw
To True Try TryCast TypeOf UInteger While
Widening With WithEvents WriteOnly Xor

Data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

Data Types Available in VB.Net

VB.Net provides a wide range of data types. The following table shows all the data types available −

Data Type Storage Allocation Value Range
Boolean Depends on implementing platform or
Byte 1 byte 0 through 255 (unsigned)
Char 2 bytes 0 through 65535 (unsigned)
Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999
Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28) with no decimal point; 0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal
Double 8 bytes

-1.79769313486231570E+308 through -4.94065645841246544E-324, for negative values

4.94065645841246544E-324 through 1.79769313486231570E+308, for positive values

Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)
Long 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807(signed)
Object

4 bytes on 32-bit platform

8 bytes on 64-bit platform

Any type can be stored in a variable of type Object
SByte 1 byte -128 through 127 (signed)
Short 2 bytes -32,768 through 32,767 (signed)
Single 4 bytes

-3.4028235E+38 through -1.401298E-45 for negative values;

1.401298E-45 through 3.4028235E+38 for positive values

String Depends on implementing platform 0 to approximately 2 billion Unicode characters
UInteger 4 bytes 0 through 4,294,967,295 (unsigned)
ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned)
User-Defined Depends on implementing platform Each member of the structure has a range determined by its data type and independent of the ranges of the other members
UShort 2 bytes 0 through 65,535 (unsigned)

The following example demonstrates use of some of the types −

The Type Conversion Functions in VB.Net

VB.Net provides the following in-line type conversion functions −

Sr.No. Functions & Description
1

Converts the expression to Boolean data type.

2

Converts the expression to Byte data type.

3

Converts the expression to Char data type.

4

Converts the expression to Date data type

5

Converts the expression to Double data type.

6

Converts the expression to Decimal data type.

7

Converts the expression to Integer data type.

8

Converts the expression to Long data type.

9

Converts the expression to Object type.

10

Converts the expression to SByte data type.

11

Converts the expression to Short data type.

12

Converts the expression to Single data type.

13

Converts the expression to String data type.

14

Converts the expression to UInt data type.

15

Converts the expression to ULng data type.

16

Converts the expression to UShort data type.

The following example demonstrates some of these functions −

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in VB.Net has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

We have already discussed various data types. The basic value types provided in VB.Net can be categorized as −

Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
Floating point types Single and Double
Decimal types Decimal
Boolean types True or False values, as assigned
Date types Date

VB.Net also allows defining other value types of variable like Enum and reference types of variables like Class . We will discuss date types and Classes in subsequent chapters.

Variable Declaration in VB.Net

The Dim statement is used for variable declaration and storage allocation for one or more variables. The Dim statement is used at module, class, structure, procedure or block level.

Syntax for variable declaration in VB.Net is −

attributelist is a list of attributes that apply to the variable. Optional.

accessmodifier defines the access levels of the variables, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.

Shared declares a shared variable, which is not associated with any specific instance of a class or structure, rather available to all the instances of the class or structure. Optional.

Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.

Static indicates that the variable will retain its value, even when the after termination of the procedure in which it is declared. Optional.

ReadOnly means the variable can be read, but not written. Optional.

WithEvents specifies that the variable is used to respond to events raised by the instance assigned to the variable. Optional.

Variablelist provides the list of variables declared.

Each variable in the variable list has the following syntax and parts −

variablename − is the name of the variable

boundslist − optional. It provides list of bounds of each dimension of an array variable.

New − optional. It creates a new instance of the class when the Dim statement runs.

datatype − Required if Option Strict is On. It specifies the data type of the variable.

initializer − Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.

Some valid variable declarations along with their definition are shown here −

Variable Initialization in VB.Net

Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −

for example,

You can initialize a variable at the time of declaration as follows −

Try the following example which makes use of various types of variables −

Accepting Values from User

The Console class in the System namespace provides a function ReadLine for accepting input from the user and store it into a variable. For example,

The following example demonstrates it −

When the above code is compiled and executed, it produces the following result (assume the user inputs Hello World) −

Lvalues and Rvalues

There are two kinds of expressions −

lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.

rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −

But following is not a valid statement and would generate compile-time error −

VB.Net - Constants and Enumerations

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.

The constants are treated just like regular variables except that their values cannot be modified after their definition.

An enumeration is a set of named integer constants.

Declaring Constants

In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values.

The syntax for the Const statement is −

attributelist − specifies the list of attributes applied to the constants; you can provide multiple attributes separated by commas. Optional.

accessmodifier − specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private.

Shadows − this makes the constant hide a programming element of identical name in a base class. Optional.

Constantlist − gives the list of names of constants declared. Required.

Where, each constant name has the following syntax and parts −

constantname − specifies the name of the constant

datatype − specifies the data type of the constant

initializer − specifies the value assigned to the constant

For example,

The following example demonstrates declaration and use of a constant value −

Print and Display Constants in VB.Net

VB.Net provides the following print and display constants −

Sr.No. Constant & Description
1

Carriage return/linefeed character combination.

2

Carriage return character.

3

Linefeed character.

4

Newline character.

5

Null character.

6

Not the same as a zero-length string (""); used for calling external procedures.

7

Error number. User-defined error numbers should be greater than this value. For example: Err.Raise(Number) = vbObjectError + 1000

8

Tab character.

9

Backspace character.

Declaring Enumerations

An enumerated type is declared using the Enum statement. The Enum statement declares an enumeration and defines the values of its members. The Enum statement can be used at the module, class, structure, procedure, or block level.

The syntax for the Enum statement is as follows −

attributelist − refers to the list of attributes applied to the variable. Optional.

accessmodifier − specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private.

Shadows − this makes the enumeration hide a programming element of identical name in a base class. Optional.

enumerationname − name of the enumeration. Required

datatype − specifies the data type of the enumeration and all its members.

memberlist − specifies the list of member constants being declared in this statement. Required.

Each member in the memberlist has the following syntax and parts:

name − specifies the name of the member. Required.

initializer − value assigned to the enumeration member. Optional.

The following example demonstrates declaration and use of the Enum variable Colors −

The modifiers are keywords added with any programming element to give some especial emphasis on how the programming element will behave or will be accessed in the program.

For example, the access modifiers: Public, Private, Protected, Friend, Protected Friend, etc., indicate the access level of a programming element like a variable, constant, enumeration or a class.

List of Available Modifiers in VB.Net

The following table provides the complete list of VB.Net modifiers −

Sr.No Modifier Description
1 Ansi Specifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the name of the external procedure being declared.
2 Assembly Specifies that an attribute at the beginning of a source file applies to the entire assembly.
3 Async Indicates that the method or lambda expression that it modifies is asynchronous. Such methods are referred to as async methods. The caller of an async method can resume its work without waiting for the async method to finish.
4 Auto The part in the Declare statement supplies the character set information for marshaling strings during a call to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules.
5 ByRef Specifies that an argument is passed by reference, i.e., the called procedure can change the value of a variable underlying the argument in the calling code. It is used under the contexts of −
6 ByVal Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable underlying the argument in the calling code. It is used under the contexts of −
7 Default Identifies a property as the default property of its class, structure, or interface.
8 Friend

Specifies that one or more declared programming elements are accessible from within the assembly that contains their declaration, not only by the component that declares them.

Friend access is often the preferred level for an application's programming elements, and Friend is the default access level of an interface, a module, a class, or a structure.

9 In It is used in generic interfaces and delegates.
10 Iterator Specifies that a function or Get accessor is an iterator. An iterator performs a custom iteration over a collection.
11 Key The Key keyword enables you to specify behavior for properties of anonymous types.
12 Module Specifies that an attribute at the beginning of a source file applies to the current assembly module. It is not same as the Module statement.
13 MustInherit Specifies that a class can be used only as a base class and that you cannot create an object directly from it.
14 MustOverride Specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can be used.
15 Narrowing Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.
16 NotInheritable Specifies that a class cannot be used as a base class.
17 NotOverridable Specifies that a property or procedure cannot be overridden in a derived class.
18 Optional Specifies that a procedure argument can be omitted when the procedure is called.
19 Out For generic type parameters, the Out keyword specifies that the type is covariant.
20 Overloads Specifies that a property or procedure redeclares one or more existing properties or procedures with the same name.
21 Overridable Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.
22 Overrides Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.
23 ParamArray ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always declared using ByVal.
24 Partial Indicates that a class or structure declaration is a partial definition of the class or structure.
25 Private Specifies that one or more declared programming elements are accessible only from within their declaration context, including from within any contained types.
26 Protected Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.
27 Public Specifies that one or more declared programming elements have no access restrictions.
28 ReadOnly Specifies that a variable or property can be read but not written.
29 Shadows Specifies that a declared programming element redeclares and hides an identically named element, or set of overloaded elements, in a base class.
30 Shared Specifies that one or more declared programming elements are associated with a class or structure at large, and not with a specific instance of the class or structure.
31 Static Specifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared.
32 Unicode Specifies that Visual Basic should marshal all strings to Unicode values regardless of the name of the external procedure being declared.
33 Widening Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.
34 WithEvents Specifies that one or more declared member variables refer to an instance of a class that can raise events.
35 WriteOnly Specifies that a property can be written but not read.

A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators, variables, literal values, constants and expressions.

Statements could be categorized as −

Declaration statements − these are the statements where you name a variable, constant, or procedure, and can also specify a data type.

Executable statements − these are the statements, which initiate actions. These statements can call a method or function, loop or branch through blocks of code or assign values or expression to a variable or constant. In the last case, it is called an Assignment statement.

Declaration Statements

The declaration statements are used to name and define procedures, variables, properties, arrays, and constants. When you declare a programming element, you can also define its data type, access level, and scope.

The programming elements you may declare include variables, constants, enumerations, classes, structures, modules, interfaces, procedures, procedure parameters, function returns, external procedure references, operators, properties, events, and delegates.

Following are the declaration statements in VB.Net −

Sr.No Statements and Description Example
1

Declares and allocates storage space for one or more variables.

2

Declares and defines one or more constants.

3

Declares an enumeration and defines the values of its members.

4

Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class comprises.

5

Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the structure comprises.

6

Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the module comprises.

7

Declares the name of an interface and introduces the definitions of the members that the interface comprises.

8

Declares the name, parameters, and code that define a Function procedure.

9

Declares the name, parameters, and code that define a Sub procedure.

10

Declares a reference to a procedure implemented in an external file.

11

Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.

12

Declares the name of a property, and the property procedures used to store and retrieve the value of the property.

13

Declares a user-defined event.

14

Used to declare a delegate.

Executable Statements

An executable statement performs an action. Statements calling a procedure, branching to another place in the code, looping through several statements, or evaluating an expression are executable statements. An assignment statement is a special case of an executable statement.

The following example demonstrates a decision making statement −

The VB.Net compiler directives give instructions to the compiler to preprocess the information before actual compilation starts. All these directives begin with #, and only white-space characters may appear before a directive on a line. These directives are not statements.

VB.Net compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In VB.Net, the compiler directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros.

Compiler Directives in VB.Net

VB.Net provides the following set of compiler directives −

The #Const Directive

The #externalsource directive, the #if...then...#else directives, the #region directive.

This directive defines conditional compiler constants. Syntax for this directive is −

constname − specifies the name of the constant. Required.

expression − it is either a literal, or other conditional compiler constant, or a combination including any or all arithmetic or logical operators except Is .

The following code demonstrates a hypothetical use of the directive −

This directive is used for indicating a mapping between specific lines of source code and text external to the source. It is used only by the compiler and the debugger has no effect on code compilation.

This directive allows including external code from an external code file into a source code file.

Syntax for this directive is −

The parameters of #ExternalSource directive are the path of external file, line number of the first line, and the line where the error occurred.

This directive conditionally compiles selected blocks of Visual Basic code.

This directive helps in collapsing and hiding sections of code in Visual Basic files.

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. VB.Net is rich in built-in operators and provides following types of commonly used operators −

Arithmetic Operators

Comparison operators, logical/bitwise operators, bit shift operators, assignment operators, miscellaneous operators.

This tutorial will explain the most commonly used operators.

Following table shows all the arithmetic operators supported by VB.Net. Assume variable A holds 2 and variable B holds 7, then −

Show Examples

Operator Description Example
^ Raises one operand to the power of another B^A will give 49
+ Adds two operands A + B will give 9
- Subtracts second operand from the first A - B will give -5
* Multiplies both operands A * B will give 14
/ Divides one operand by another and returns a floating point result B / A will give 3.5
\ Divides one operand by another and returns an integer result B \ A will give 3
MOD Modulus Operator and remainder of after an integer division B MOD A will give 1

Following table shows all the comparison operators supported by VB.Net. Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example
= Checks if the values of two operands are equal or not; if yes, then condition becomes true. (A = B) is not true.
<> Checks if the values of two operands are equal or not; if values are not equal, then condition becomes true. (A <> B) is true.
> Checks if the value of left operand is greater than the value of right operand; if yes, then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand; if yes, then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand; if yes, then condition becomes true. (A <= B) is true.

Apart from the above, VB.Net provides three more comparison operators, which we will be using in forthcoming chapters; however, we give a brief description here.

Is Operator − It compares two object reference variables and determines if two object references refer to the same object without performing value comparisons. If object1 and object2 both refer to the exact same object instance, result is True ; otherwise, result is False.

IsNot Operator − It also compares two object reference variables and determines if two object references refer to different objects. If object1 and object2 both refer to the exact same object instance, result is False ; otherwise, result is True.

Like Operator − It compares a string against a pattern.

Following table shows all the logical operators supported by VB.Net. Assume variable A holds Boolean value True and variable B holds Boolean value False, then −

Operator Description Example
And It is the logical as well as bitwise AND operator. If both the operands are true, then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions. (A And B) is False.
Or It is the logical as well as bitwise OR operator. If any of the two operands is true, then condition becomes true. This operator does not perform short-circuiting, i.e., it evaluates both the expressions. (A Or B) is True.
Not It is the logical as well as bitwise NOT operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. Not(A And B) is True.
Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns True if both expressions are True or both expressions are False; otherwise it returns False. This operator does not perform short-circuiting, it always evaluates both expressions and there is no short-circuiting counterpart of this operator. A Xor B is True.
AndAlso It is the logical AND operator. It works only on Boolean data. It performs short-circuiting. (A AndAlso B) is False.
OrElse It is the logical OR operator. It works only on Boolean data. It performs short-circuiting. (A OrElse B) is True.
IsFalse It determines whether an expression is False.
IsTrue It determines whether an expression is True.

We have already discussed the bitwise operators. The bit shift operators perform the shift operations on binary values. Before coming into the bit shift operators, let us understand the bit operations.

Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and ^ are as follows −

p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The Bit shift operators are >> and << for left shift and right shift, respectively.

Assume that the variable A holds 60 and variable B holds 13, then −

Operator Description Example
And Bitwise AND Operator copies a bit to the result if it exists in both operands. (A AND B) will give 12, which is 0000 1100
Or Binary OR Operator copies a bit if it exists in either operand. (A Or B) will give 61, which is 0011 1101
Xor Binary XOR Operator copies the bit if it is set in one operand but not both. (A Xor B) will give 49, which is 0011 0001
Not Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (Not A ) will give -61, which is 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240, which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15, which is 0000 1111

There are following assignment operators supported by VB.Net −

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assigns the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand (floating point division) C /= A is equivalent to C = C / A
\= Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand (Integer division) C \= A is equivalent to C = C \A
^= Exponentiation and assignment operator. It raises the left operand to the power of the right operand and assigns the result to left operand. C^=A is equivalent to C = C ^ A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Concatenates a String expression to a String variable or property and assigns the result to the variable or property.

Str1 &= Str2 is same as

Str1 = Str1 & Str2

There are few other important operators supported by VB.Net.

Operator Description Example
AddressOf Returns the address of a procedure.
Await It is applied to an operand in an asynchronous method or lambda expression to suspend execution of the method until the awaited task completes.
GetType It returns a Type object for the specified type. The Type object provides information about the type such as its properties, methods, and events.
Function Expression It declares the parameters and code that define a function lambda expression.
If It uses short-circuit evaluation to conditionally return one of two values. The If operator can be called with three arguments or with two arguments.

Operators Precedence in VB.Net

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Operator Precedence
Await Highest
Exponentiation (^)
Unary identity and negation (+, -)
Multiplication and floating-point division (*, /)
Integer division (\)
Modulus arithmetic (Mod)
Addition and subtraction (+, -)
Arithmetic bit shift (<<, >>)
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor) Lowest

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the programming languages −

Decision making statements in VB.Net

VB.Net provides the following types of decision making statements. Click the following links to check their details.

Statement Description

An consists of a boolean expression followed by one or more statements.

An can be followed by an optional , which executes when the boolean expression is false.

You can use one or statement inside another or statement(s).

A statement allows a variable to be tested for equality against a list of values.

You can use one statement inside another statement(s).

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −

Loop Architecture

VB.Net provides following types of loops to handle looping requirements. Click the following links to check their details.

Loop Type Description

It repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement.

It repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes.

It repeats a group of statements for each element in a collection. This loop is used for accessing and manipulating all elements in an array or a VB.Net collection.

It executes a series of statements as long as a given condition is True.

It is not exactly a looping construct. It executes a series of statements that repeatedly refer to a single object or structure.

You can use one or more loops inside any another While, For or Do loop.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

VB.Net provides the following control statements. Click the following links to check their details.

Control Statement Description

Terminates the or statement and transfers execution to the statement immediately following the loop or select case.

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Transfers control to the labeled statement. Though it is not advised to use GoTo statement in your program.

In VB.Net, you can use strings as array of characters, however, more common practice is to use the String keyword to declare a string variable. The string keyword is an alias for the System.String class.

Creating a String Object

You can create string object using one of the following methods −

By assigning a string literal to a String variable

By using a String class constructor

By using the string concatenation operator (+)

By retrieving a property or calling a method that returns a string

By calling a formatting method to convert a value or object to its string representation

The following example demonstrates this −

Properties of the String Class

The String class has the following two properties −

Sr.No Property Name & Description
1

Gets the object at a specified position in the current object.

2

Gets the number of characters in the current String object.

Methods of the String Class

The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods −

Sr.No Method Name & Description
1

Compares two specified string objects and returns an integer that indicates their relative position in the sort order.

2

Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true.

3

Concatenates two string objects.

4

Concatenates three string objects.

5

Concatenates four string objects.

6

Returns a value indicating whether the specified string object occurs within this string.

7

Creates a new String object with the same value as the specified string.

8

Copies a specified number of characters from a specified position of the string object to a specified position in an array of Unicode characters.

9

Determines whether the end of the string object matches the specified string.

10

Determines whether the current string object and the specified string object have the same value.

11

Determines whether two specified string objects have the same value.

12

Replaces one or more format items in a specified string with the string representation of a specified object.

13

Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.

14

Returns the zero-based index of the first occurrence of the specified string in this instance.

15

Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position.

16

Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position.

17

Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

18

Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position.

19

Returns a new string in which a specified string is inserted at a specified index position in the current string object.

20

Indicates whether the specified string is null or an Empty string.

21

Concatenates all the elements of a string array, using the specified separator between each element.

22

Concatenates the specified elements of a string array, using the specified separator between each element.

23

Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object.

24

Returns the zero-based index position of the last occurrence of a specified string within the current string object.

25

Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.

26

Removes the specified number of characters in the current string beginning at a specified position and returns the string.

27

Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.

28

Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.

29

Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array.

30

Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return.

31

Determines whether the beginning of this string instance matches the specified string.

32

Returns a Unicode character array with all the characters in the current string object.

33

Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length.

34

Returns a copy of this string converted to lowercase.

35

Returns a copy of this string converted to uppercase.

36

Removes all leading and trailing white-space characters from the current String object.

The above list of methods is not exhaustive, please visit MSDN library for the complete list of methods and String class constructors.

The following example demonstrates some of the methods mentioned above −

Comparing Strings

String Contains String

Getting a Substring:

Joining Strings

Most of the softwares you write need implementing some form of date functions returning current date and time. Dates are so much part of everyday life that it becomes easy to work with them without thinking. VB.Net also provides powerful tools for date arithmetic that makes manipulating dates easy.

The Date data type contains date values, time values, or date and time values. The default value of Date is 0:00:00 (midnight) on January 1, 0001. The equivalent .NET data type is System.DateTime .

The DateTime structure represents an instant in time, typically expressed as a date and time of day

You can also get the current date and time from the DateAndTime class.

The DateAndTime module contains the procedures and properties used in date and time operations.

Both the DateTime structure and the DateAndTime module contain properties like and , so often beginners find it confusing. The DateAndTime class belongs to the Microsoft.VisualBasic namespace and the DateTime structure belongs to the System namespace.
Therefore, using the later would help you in porting your code to another .Net language like C#. However, the DateAndTime class/module contains all the legacy date functions available in Visual Basic.

Properties and Methods of the DateTime Structure

The following table lists some of the commonly used properties of the DateTime Structure −

Sr.No Property Description
1 Gets the date component of this instance.
2 Gets the day of the month represented by this instance.
3 Gets the day of the week represented by this instance.
4 Gets the day of the year represented by this instance.
5 Gets the hour component of the date represented by this instance.
6 Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
7 Gets the milliseconds component of the date represented by this instance.
8 Gets the minute component of the date represented by this instance.
9 Gets the month component of the date represented by this instance.
10 Gets a object that is set to the current date and time on this computer, expressed as the local time.
11 Gets the seconds component of the date represented by this instance.
12 Gets the number of ticks that represent the date and time of this instance.
13 Gets the time of day for this instance.
14 Gets the current date.
15 Gets a object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
16 Gets the year component of the date represented by this instance.

The following table lists some of the commonly used methods of the DateTime structure −

Sr.No Method Name & Description
1

Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

2

Returns a new DateTime that adds the specified number of days to the value of this instance.

3

Returns a new DateTime that adds the specified number of hours to the value of this instance.

4

Returns a new DateTime that adds the specified number of minutes to the value of this instance.

5

Returns a new DateTime that adds the specified number of months to the value of this instance.

6

Returns a new DateTime that adds the specified number of seconds to the value of this instance.

7

Returns a new DateTime that adds the specified number of years to the value of this instance.

8

Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.

9

Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.

10

Returns a value indicating whether the value of this instance is equal to the value of the specified DateTime instance.

11

Returns a value indicating whether two DateTime instances have the same date and time value.

12

Converts the value of the current DateTime object to its equivalent string representation.

The above list of methods is not exhaustive, please visit Microsoft documentation for the complete list of methods and properties of the DateTime structure.

Creating a DateTime Object

You can create a DateTime object in one of the following ways −

By calling a DateTime constructor from any of the overloaded DateTime constructors.

By assigning the DateTime object a date and time value returned by a property or method.

By parsing the string representation of a date and time value.

By calling the DateTime structure's implicit default constructor.

When the above code was compiled and executed, it produces the following result −

Getting the Current Date and Time

The following programs demonstrate how to get the current date and time in VB.Net −

Current Time −

Current Date −

Formatting Date

A Date literal should be enclosed within hash signs (# #), and specified in the format M/d/yyyy, for example #12/16/2012#. Otherwise, your code may change depending on the locale in which your application is running.

For example, you specified Date literal of #2/6/2012# for the date February 6, 2012. It is alright for the locale that uses mm/dd/yyyy format. However, in a locale that uses dd/mm/yyyy format, your literal would compile to June 2, 2012. If a locale uses another format say, yyyy/mm/dd, the literal would be invalid and cause a compiler error.

To convert a Date literal to the format of your locale or to a custom format, use the Format function of String class, specifying either a predefined or user-defined date format.

The following example demonstrates this.

Predefined Date/Time Formats

The following table identifies the predefined date and time format names. These may be used by name as the style argument for the Format function −

Format Description
Displays a date and/or time. For example, 1/12/2012 07:07:30 AM.
Displays a date according to your current culture's long date format. For example, Sunday, December 16, 2012.
Displays a date using your current culture's short date format. For example, 12/12/2012.
Displays a time using your current culture's long time format; typically includes hours, minutes, seconds. For example, 01:07:30 AM.
Displays a time using your current culture's short time format. For example, 11:07 AM.
Displays the long date and short time according to your current culture's format. For example, Sunday, December 16, 2012 12:15 AM.
Displays the long date and long time according to your current culture's format. For example, Sunday, December 16, 2012 12:15:31 AM.
Displays the short date and short time according to your current culture's format. For example, 12/16/2012 12:15 AM.
Displays the month and the day of a date. For example, December 16.
Formats the date according to the RFC1123Pattern property.
Formats the date and time as a sortable index. For example, 2012-12-16T12:07:31.
Formats the date and time as a GMT sortable index. For example, 2012-12-16 12:15:31Z.
Formats the date and time with the long date and long time as GMT. For example, Sunday, December 16, 2012 6:07:31 PM.
Formats the date as the year and month. For example, December, 2012.

For other formats like user-defined formats, please consult Microsoft Documentation .

Properties and Methods of the DateAndTime Class

The following table lists some of the commonly used properties of the DateAndTime Class −

Sr.No Property & Description
1

Returns or sets a String value representing the current date according to your system.

2

Returns a Date value containing the current date and time according to your system.

3

Returns or sets a Date value containing the current time of day according to your system.

4

Returns a Double value representing the number of seconds elapsed since midnight.

5

Returns or sets a String value representing the current time of day according to your system.

6

Gets the current date.

The following table lists some of the commonly used methods of the DateAndTime class −

Sr.No Method Name & Description
1

Returns a Date value containing a date and time value to which a specified time interval has been added.

2

Returns a Date value containing a date and time value to which a specified time interval has been added.

3

Returns a Long value specifying the number of time intervals between two Date values.

4

Returns an Integer value containing the specified component of a given Date value.

5

Returns an Integer value from 1 through 31 representing the day of the month.

6

Returns an Integer value from 0 through 23 representing the hour of the day.

7

Returns an Integer value from 0 through 59 representing the minute of the hour.

8

Returns an Integer value from 1 through 12 representing the month of the year.

9

Returns a String value containing the name of the specified month.

10

Returns an Integer value from 0 through 59 representing the second of the minute.

11

Returns a string that represents the current object.

12

Returns an Integer value containing a number representing the day of the week.

13

Returns a String value containing the name of the specified weekday.

14

Returns an Integer value from 1 through 9999 representing the year.

The above list is not exhaustive. For complete list of properties and methods of the DateAndTime class, please consult Microsoft Documentation .

The following program demonstrates some of these and methods −

An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Arrays in VB.Net

Creating Arrays in VB.Net

To declare an array in VB.Net, you use the Dim statement. For example,

You can also initialize the array elements while declaring the array. For example,

The elements in an array can be stored and accessed by using the index of the array. The following program demonstrates this −

Dynamic Arrays

Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program. You can declare a dynamic array using the ReDim statement.

Syntax for ReDim statement −

The Preserve keyword helps to preserve the data in an existing array, when you resize it.

arrayname is the name of the array to re-dimension.

subscripts specifies the new dimension.

Multi-Dimensional Arrays

VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays.

You can declare a 2-dimensional array of strings as −

or, a 3-dimensional array of Integer variables −

The following program demonstrates creating and using a 2-dimensional array −

Jagged Array

A Jagged array is an array of arrays. The following code shows declaring a jagged array named scores of Integers −

The following example illustrates using a jagged array −

The Array Class

The Array class is the base class for all the arrays in VB.Net. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays.

Properties of the Array Class

The following table provides some of the most commonly used properties of the Array class −

Sr.No Property Name & Description
1

Gets a value indicating whether the Array has a fixed size.

2

Gets a value indicating whether the Array is read-only.

3

Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.

4

Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.

5

Gets the rank (number of dimensions) of the Array.

Methods of the Array Class

The following table provides some of the most commonly used methods of the Array class −

Sr.No Method Name & Description
1

Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.

2

Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.

3

Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit integer.

4

Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.

5

Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array.

6

Gets the lower bound of the specified dimension in the Array.

7

Gets the Type of the current instance (Inherited from Object).

8

Gets the upper bound of the specified dimension in the Array.

9

Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.

10

Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.

11

Reverses the sequence of the elements in the entire one-dimensional Array.

12

Sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.

13

Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

14

Returns a string that represents the current object (Inherited from Object).

For complete list of Array class properties and methods, please consult Microsoft documentation.

The following program demonstrates use of some of the methods of the Array class:

Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces.

Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index, etc. These classes create collections of objects of the Object class, which is the base class for all data types in VB.Net.

Various Collection Classes and Their Usage

The following are the various commonly used classes of the System.Collection namespace. Click the following links to check their details.

Class Description and Useage

It represents ordered collection of an object that can be individually.

It is basically an alternative to an array. However, unlike array, you can add and remove items from a list at a specified position using an and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list.

It uses a to access the elements in the collection.

A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a pair. The key is used to access the items in the collection.

It uses a as well as an to access the items in a list.

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.

It represents a collection of object.

It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called the item, and when you remove it, it is called the item.

It represents a collection of object.

It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called , and when you remove an item, it is called .

It represents an array of the using the values 1 and 0.

It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an , which starts from zero.

A procedure is a group of statements that together perform a task when called. After the procedure is executed, the control returns to the statement calling the procedure. VB.Net has two types of procedures −

Sub procedures or Subs

Functions return a value, whereas Subs do not return a value.

Defining a Function

The Function statement is used to declare the name, parameter and the body of a function. The syntax for the Function statement is −

Modifiers − specify the access level of the function; possible values are: Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.

FunctionName − indicates the name of the function

ParameterList − specifies the list of the parameters

ReturnType − specifies the data type of the variable the function returns

Following code snippet shows a function FindMax that takes two integer values and returns the larger of the two.

Function Returning a Value

In VB.Net, a function can return a value to the calling code in two ways −

By using the return statement

By assigning the value to the function name

The following example demonstrates using the FindMax function −

Recursive Function

A function can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function −

Param Arrays

At times, while declaring a function or sub procedure, you are not sure of the number of arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into help at these times.

Passing Arrays as Function Arguments

You can pass an array as a function argument in VB.Net. The following example demonstrates this −

VB.Net - Sub Procedures

As we mentioned in the previous chapter, Sub procedures are procedures that do not return any value. We have been using the Sub procedure Main in all our examples. We have been writing console applications so far in these tutorials. When these applications start, the control goes to the Main Sub procedure, and it in turn, runs any other statements constituting the body of the program.

Defining Sub Procedures

The Sub statement is used to declare the name, parameter and the body of a sub procedure. The syntax for the Sub statement is −

Modifiers − specify the access level of the procedure; possible values are - Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.

SubName − indicates the name of the Sub

The following example demonstrates a Sub procedure CalculatePay that takes two parameters hours and wages and displays the total pay of an employee −

Passing Parameters by Value

This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. So, the changes made to the parameter inside the method have no effect on the argument.

In VB.Net, you declare the reference parameters using the ByVal keyword. The following example demonstrates the concept −

It shows that there is no change in the values though they had been changed inside the function.

Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.

In VB.Net, you declare the reference parameters using the ByRef keyword. The following example demonstrates this −

When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

Objects are instances of a class. The methods and variables that constitute a class are called members of the class.

Class Definition

A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End Class statement. Following is the general form of a class definition −

attributelist is a list of attributes that apply to the class. Optional.

accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.

MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional.

NotInheritable specifies that the class cannot be used as a base class.

Partial indicates a partial definition of the class.

Inherits specifies the base class it is inheriting from.

Implements specifies the interfaces the class is inheriting from.

The following example demonstrates a Box class, with three data members, length, breadth and height −

Member Functions and Encapsulation

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member and has access to all the members of a class for that object.

Member variables are attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.

Let us put above concepts to set and get the value of different class members in a class −

Constructors and Destructors

A class constructor is a special member Sub of a class that is executed whenever we create new objects of that class. A constructor has the name New and it does not have any return type.

Following program explains the concept of constructor −

A default constructor does not have any parameter, but if you need, a constructor can have parameters. Such constructors are called parameterized constructors . This technique helps you to assign initial value to an object at the time of its creation as shown in the following example −

A destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope.

A destructor has the name Finalize and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories, etc.

Destructors cannot be inherited or overloaded.

Following example explains the concept of destructor −

Shared Members of a VB.Net Class

We can define class members as static using the Shared keyword. When we declare a member of a class as Shared, it means no matter how many objects of the class are created, there is only one copy of the member.

The keyword Shared implies that only one instance of the member exists for a class. Shared variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it.

Shared variables can be initialized outside the member function or class definition. You can also initialize Shared variables inside the class definition.

You can also declare a member function as Shared. Such functions can access only Shared variables. The Shared functions exist even before the object is created.

The following example demonstrates the use of shared members −

Inheritance

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

Base & Derived Classes

A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.

The syntax used in VB.Net for creating derived classes is as follows −

Consider a base class Shape and its derived class Rectangle −

Base Class Initialization

The derived class inherits the base class member variables and member methods. Therefore, the super class object should be created before the subclass is created. The super class or the base class is implicitly known as MyBase in VB.Net

The following program demonstrates this −

VB.Net supports multiple inheritance.

An exception is a problem that arises during the execution of a program. An exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. VB.Net exception handling is built upon four keywords - Try , Catch , Finally and Throw .

Try − A Try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more Catch blocks.

Catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The Catch keyword indicates the catching of an exception.

Finally − The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

Throw − A program throws an exception when a problem shows up. This is done using a Throw keyword.

Assuming a block will raise an exception, a method catches an exception using a combination of the Try and Catch keywords. A Try/Catch block is placed around the code that might generate an exception. Code within a Try/Catch block is referred to as protected code, and the syntax for using Try/Catch looks like the following −

You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.

Exception Classes in .Net Framework

In the .Net Framework, exceptions are represented by classes. The exception classes in .Net Framework are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.

The System.SystemException class is the base class for all predefined system exception.

The following table provides some of the predefined exception classes derived from the Sytem.SystemException class −

Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type.
System.NullReferenceException Handles errors generated from deferencing a null object.
System.DivideByZeroException Handles errors generated from dividing a dividend with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException Handles errors generated from insufficient free memory.
System.StackOverflowException Handles errors generated from stack overflow.

Handling Exceptions

VB.Net provides a structured solution to the exception handling problems in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.

These error handling blocks are implemented using the Try , Catch and Finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs −

Creating User-Defined Exceptions

You can also define your own exception. User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this −

Throwing Objects

You can throw an object if it is either directly or indirectly derived from the System.Exception class.

You can use a throw statement in the catch block to throw the present object as −

A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream .

The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream . The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).

VB.Net I/O Classes

The System.IO namespace has various classes that are used for performing various operations with files, like creating and deleting files, reading from or writing to a file, closing a file, etc.

The following table shows some commonly used non-abstract classes in the System.IO namespace −

I/O Class Description
BinaryReader Reads primitive data from a binary stream.
BinaryWriter Writes primitive data in binary format.
BufferedStream A temporary storage for a stream of bytes.
Directory Helps in manipulating a directory structure.
DirectoryInfo Used for performing operations on directories.
DriveInfo Provides information for the drives.
File Helps in manipulating files.
FileInfo Used for performing operations on files.
FileStream Used to read from and write to any location in a file.
MemoryStream Used for random access of streamed data stored in memory.
Path Performs operations on path information.
StreamReader Used for reading characters from a byte stream.
StreamWriter Is used for writing characters to a stream.
StringReader Is used for reading from a string buffer.
StringWriter Is used for writing into a string buffer.

The FileStream Class

The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.

You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows −

For example, for creating a FileStream object F for reading a file named sample.txt −

Parameter Description
FileMode

The enumerator defines various methods for opening files. The members of the FileMode enumerator are −

− It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.

− It creates a new file.

− It specifies to the operating system that it should create a new file.

− It opens an existing file.

− It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.

− It opens an existing file and truncates its size to zero bytes.

FileAccess

enumerators have members: , and .

FileShare

enumerators have the following members −

− It allows a file handle to pass inheritance to the child processes

− It declines sharing of the current file

− It allows opening the file for reading

− It allows opening the file for reading and writing

− It allows opening the file for writing

The following program demonstrates use of the FileStream class −

Advanced File Operations in VB.Net

The preceding example provides simple file operations in VB.Net. However, to utilize the immense powers of System.IO classes, you need to know the commonly used properties and methods of these classes.

We will discuss these classes and the operations they perform in the following sections. Please click the links provided to get to the individual sections −

Sr.No. Topic and Description
1

It involves reading from and writing into text files. The and classes help to accomplish it.

2

It involves reading from and writing into binary files. The and classes help to accomplish this.

3

It gives a VB.Net programmer the ability to browse and locate Windows files and directories.

An object is a type of user interface element you create on a Visual Basic form by using a toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic control consists of three important elements −

Properties which describe the object,

Methods cause an object to do something and

Events are what happens when an object does something.

Control Properties

All the Visual Basic Objects can be moved, resized or customized by setting their properties. A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color.

Properties can be set at design time by using the Properties window or at run time by using statements in the program code.

Object is the name of the object you're customizing.

Property is the characteristic you want to change.

Value is the new property setting.

You can set any of the form properties using Properties Window. Most of the properties can be set or read during application execution. You can refer to Microsoft documentation for a complete list of properties associated with different controls and restrictions applied to them.

Control Methods

A method is a procedure created as a member of a class and they cause an object to do something. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes −

If you are using a control such as one of those provided by the Toolbox, you can call any of its public methods. The requirements of such a method depend on the class being used.

If none of the existing methods can perform your desired task, you can add a method to a class.

For example, the MessageBox control has a method named Show, which is called in the code snippet below −

Control Events

An event is a signal that informs an application that something important has occurred. For example, when a user clicks a control on a form, the form can raise a Click event and call a procedure that handles the event. There are various types of events associated with a Form like click, double click, close, load, resize, etc.

Following is the default structure of a form Load event handler subroutine. You can see this code by double clicking the code which will give you a complete list of the all events associated with Form control −

Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar way, you can check stub code for click, double click. If you want to initialize some variables like properties, etc., then you will keep such code inside Form1_Load() subroutine. Here, important point to note is the name of the event handler, which is by default Form1_Load, but you can change this name based on your naming convention you use in your application programming.

Basic Controls

VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities of all these controls are defined in the respective control classes. The control classes are defined in the System.Windows.Forms namespace.

The following table lists some of the commonly used controls −

Sr.No. Widget & Description
1

The container for all the controls that make up the user interface.

2

It represents a Windows text box control.

3

It represents a standard Windows label.

4

It represents a Windows button control.

5

It represents a Windows control to display a list of items.

6

It represents a Windows combo box control.

7

It enables the user to select a single option from a group of choices when paired with other RadioButton controls.

8

It represents a Windows CheckBox.

9

It represents a Windows picture box control for displaying an image.

10

It represents a Windows progress bar control.

11

It Implements the basic functionality of a scroll bar control.

12

It represents a Windows control that allows the user to select a date and a time and to display the date and time with a specified format.

13

It displays a hierarchical collection of labeled items, each represented by a TreeNode.

14

It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views.

There are many built-in dialog boxes to be used in Windows forms for various tasks like opening and saving files, printing a page, providing choices for colors, fonts, page setup, etc., to the user of an application. These built-in dialog boxes reduce the developer's time and workload.

All of these dialog box control classes inherit from the CommonDialog class and override the RunDialog() function of the base class to create the specific dialog box.

The RunDialog() function is automatically invoked when a user of a dialog box calls its ShowDialog() function.

The ShowDialog method is used to display all the dialog box controls at run-time. It returns a value of the type of DialogResult enumeration. The values of DialogResult enumeration are −

Abort − returns DialogResult.Abort value, when user clicks an Abort button.

Cancel − returns DialogResult.Cancel, when user clicks a Cancel button.

Ignore − returns DialogResult.Ignore, when user clicks an Ignore button.

No − returns DialogResult.No, when user clicks a No button.

None − returns nothing and the dialog box continues running.

OK − returns DialogResult.OK, when user clicks an OK button

Retry − returns DialogResult.Retry , when user clicks an Retry button

Yes − returns DialogResult.Yes, when user clicks an Yes button

The following diagram shows the common dialog class inheritance −

VB.Net Dialog Boxes

All these above-mentioned classes have corresponding controls that could be added from the Toolbox during design time. You can include relevant functionality of these classes to your application, either by instantiating the class programmatically or by using relevant controls.

When you double click any of the dialog controls in the toolbox or drag the control onto the form, it appears in the Component tray at the bottom of the Windows Forms Designer, they do not directly show up on the form.

The following table lists the commonly used dialog box controls. Click the following links to check their detail −

Sr.No. Control & Description
1

It represents a common dialog box that displays available colors along with controls that enable the user to define custom colors.

2

It prompts the user to choose a font from among those installed on the local computer and lets the user select the font, font size, and color.

3

It prompts the user to open a file and allows the user to select a file to open.

4

It prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data.

5

It lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application.

VB.Net - Advanced Form

In this chapter, let us study the following concepts −

Adding menus and sub menus in an application

Adding the cut, copy and paste functionalities in a form

Anchoring and docking controls in a form

Modal forms

Adding Menus and Sub Menus in an Application

Traditionally, the Menu , MainMenu , ContextMenu , and MenuItem classes were used for adding menus, sub-menus and context menus in a Windows application.

Now, the MenuStrip , the ToolStripMenuItem , ToolStripDropDown and ToolStripDropDownMenu controls replace and add functionality to the Menu-related controls of previous versions. However, the old control classes are retained for both backward compatibility and future use.

Let us create a typical windows main menu bar and sub menus using the old version controls first since these controls are still much used in old applications.

Following is an example, which shows how we create a menu bar with menu items: File, Edit, View and Project. The File menu has the sub menus New, Open and Save.

Let's double click on the Form and put the following code in the opened window.

When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −

VB.Net Menu Example

Windows Forms contain a rich set of classes for creating your own custom menus with modern appearance, look and feel. The MenuStrip , ToolStripMenuItem , ContextMenuStrip controls are used to create menu bars and context menus efficiently.

Click the following links to check their details −

Sr.No. Control & Description
1

It provides a menu system for a form.

2

It represents a selectable option displayed on a or . The ToolStripMenuItem control replaces and adds functionality to the MenuItem control of previous versions.

3

It represents a shortcut menu.

Adding the Cut, Copy and Paste Functionalities in a Form

The methods exposed by the ClipBoard class are used for adding the cut, copy and paste functionalities in an application. The ClipBoard class provides methods to place data on and retrieve data from the system Clipboard.

It has the following commonly used methods −

Sr.No. Method Name & Description
1

Removes all data from the Clipboard.

2

Indicates whether there is data on the Clipboard that is in the specified format or can be converted to that format.

3

Indicates whether there is data on the Clipboard that is in the Bitmap format or can be converted to that format.

4

Indicates whether there is data on the Clipboard in the Text or UnicodeText format, depending on the operating system.

5

Retrieves data from the Clipboard in the specified format.

6

Retrieves the data that is currently on the system Clipboard.

7

Retrieves an image from the Clipboard.

8

Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on the operating system.

9

Retrieves text data from the Clipboard in the format indicated by the specified TextDataFormat value.

10

Clears the Clipboard and then adds data in the specified format.

11

Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending on the operating system.

Following is an example, which shows how we cut, copy and paste data using methods of the Clipboard class. Take the following steps −

Add a rich text box control and three button controls on the form.

Change the text property of the buttons to Cut, Copy and Paste, respectively.

Double click on the buttons to add the following code in the code editor −

VB.Net Cut, Paste, Copy Example

Enter some text and check how the buttons work.

Anchoring and Docking Controls in a Form

Anchoring allows you to set an anchor position for a control to the edges of its container control, for example, the form. The Anchor property of the Control class allows you to set values of this property. The Anchor property gets or sets the edges of the container to which a control is bound and determines how a control is resized with its parent.

When you anchor a control to a form, the control maintains its distance from the edges of the form and its anchored position, when the form is resized.

You can set the Anchor property values of a control from the Properties window −

VB.Net Anchoring of Controls

For example, let us add a Button control on a form and set its anchor property to Bottom, Right. Run this form to see the original position of the Button control with respect to the form.

VB.Net Anchoring Example

Now, when you stretch the form, the distance between the Button and the bottom right corner of the form remains same.

VB.Net Anchoring Example

Docking of a control means docking it to one of the edges of its container. In docking, the control fills certain area of the container completely.

The Dock property of the Control class does this. The Dock property gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent.

You can set the Dock property values of a control from the Properties window −

VB.Net Docking of Controls

For example, let us add a Button control on a form and set its Dock property to Bottom. Run this form to see the original position of the Button control with respect to the form.

VB.Net Docking Example

Now, when you stretch the form, the Button resizes itself with the form.

VB.Net Docking Example

Modal Forms

Modal Forms are those forms that need to be closed or hidden before you can continue working with the rest of the application. All dialog boxes are modal forms. A MessageBox is also a modal form.

You can call a modal form by two ways −

Calling the ShowDialog method

Calling the Show method

Let us take up an example in which we will create a modal form, a dialog box. Take the following steps −

Add a form, Form1 to your application, and add two labels and a button control to Form1

Change the text properties of the first label and the button to 'Welcome to Tutorials Point' and 'Enter your Name', respectively. Keep the text properties of the second label as blank.

VB.Net Modal Form Example

Add a new Windows Form, Form2, and add two buttons, one label, and a text box to Form2.

Change the text properties of the buttons to OK and Cancel, respectively. Change the text properties of the label to 'Enter your name:'.

Set the FormBorderStyle property of Form2 to FixedDialog , for giving it a dialog box border.

Set the ControlBox property of Form2 to False.

Set the ShowInTaskbar property of Form2 to False.

Set the DialogResult property of the OK button to OK and the Cancel button to Cancel.

VB.Net Modal Form Example

Add the following code snippets in the Form2_Load method of Form2 −

Add the following code snippets in the Button1_Click method of Form1 −

VB.Net Modal Form Example

Clicking on the 'Enter your Name' button displays the second form −

VB.Net Modal Form Example

Clicking on the OK button takes the control and information back from the modal form to the previous form −

VB.Net Modal Form Example

Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence like system generated notifications. Applications need to respond to events when they occur.

Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples of events. An event is an action that calls a function or may cause another event. Event handlers are functions that tell how to respond to an event.

VB.Net is an event-driven language. There are mainly two types of events −

Mouse events

Keyboard events

Handling Mouse Events

Mouse events occur with mouse movements in forms and controls. Following are the various mouse events related with a Control class −

MouseDown − it occurs when a mouse button is pressed

MouseEnter − it occurs when the mouse pointer enters the control

MouseHover − it occurs when the mouse pointer hovers over the control

MouseLeave − it occurs when the mouse pointer leaves the control

MouseMove − it occurs when the mouse pointer moves over the control

MouseUp − it occurs when the mouse pointer is over the control and the mouse button is released

MouseWheel − it occurs when the mouse wheel moves and the control has focus

The event handlers of the mouse events get an argument of type MouseEventArgs . The MouseEventArgs object is used for handling mouse events. It has the following properties −

Buttons − indicates the mouse button pressed

Clicks − indicates the number of clicks

Delta − indicates the number of detents the mouse wheel rotated

X − indicates the x-coordinate of mouse click

Y − indicates the y-coordinate of mouse click

Following is an example, which shows how to handle mouse events. Take the following steps −

Add three labels, three text boxes and a button control in the form.

Change the text properties of the labels to - Customer ID, Name and Address, respectively.

Change the name properties of the text boxes to txtID, txtName and txtAddress, respectively.

Change the text property of the button to 'Submit'.

Add the following code in the code editor window −

Event Handling Example1

Try to enter text in the text boxes and check the mouse events −

Event Handling Result Form

Handling Keyboard Events

Following are the various keyboard events related with a Control class −

KeyDown − occurs when a key is pressed down and the control has focus

KeyPress − occurs when a key is pressed and the control has focus

KeyUp − occurs when a key is released while the control has focus

The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs . This object has the following properties −

Alt − it indicates whether the ALT key is pressed

Control − it indicates whether the CTRL key is pressed

Handled − it indicates whether the event is handled

KeyCode − stores the keyboard code for the event

KeyData − stores the keyboard data for the event

KeyValue − stores the keyboard value for the event

Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed

Shift − it indicates if the Shift key is pressed

Handled − indicates if the KeyPress event is handled

KeyChar − stores the character corresponding to the key pressed

Let us continue with the previous example to show how to handle keyboard events. The code will verify that the user enters some numbers for his customer ID and age.

Add a label with text Property as 'Age' and add a corresponding text box named txtAge.

Add the following codes for handling the KeyUP events of the text box txtID.

VB.Net Event Example

If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning message box and clears the respective text −

VB.Net Event Example

A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.

Constructs for Defining Regular Expressions

There are various categories of characters, operators, and constructs that lets you to define regular expressions. Click the following links to find these constructs.

Character escapes

Character classes

Grouping constructs

Quantifiers

Backreference constructs

Alternation constructs

Substitutions

Miscellaneous constructs

The Regex Class

The Regex class is used for representing a regular expression.

The Regex class has the following commonly used methods −

Sr.No. Methods & Description
1

Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

2

Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.

3

Indicates whether the specified regular expression finds a match in the specified input string.

4

Searches the specified input string for all occurrences of a regular expression.

5

In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.

6

Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

For the complete list of methods and properties, please consult Microsoft documentation.

The following example matches words that start with 'S' −

The following example matches words that start with 'm' and ends with 'e' −

This example replaces extra white space −

Applications communicate with a database, firstly, to retrieve the data stored there and present it in a user-friendly way, and secondly, to update the database by inserting, modifying and deleting data.

Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework that is used by the .Net applications for retrieving, accessing and updating data.

ADO.Net Object Model

ADO.Net object model is nothing but the structured process flow through various components. The object model can be pictorially described as −

ADO.Net objects

The data residing in a data store or database is retrieved through the data provider . Various components of the data provider retrieve data for the application and update data.

An application accesses data either through a dataset or a data reader.

Datasets store data in a disconnected cache and the application retrieves data from it.

Data readers provide data to the application in a read-only and forward-only mode.

Data Provider

A data provider is used for connecting to a database, executing commands and retrieving data, storing it in a dataset, reading the retrieved data and updating the database.

The data provider in ADO.Net consists of the following four objects −

Sr.No. Objects & Description
1

This component is used to set up a connection with a data source.

2

A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data source.

3

Data reader is used to retrieve data from a data source in a read-only and forward-only mode.

4

This is integral to the working of ADO.Net since data is transferred to and from a database through a data adapter. It retrieves data from a database into a dataset and updates the database. When changes are made to the dataset, the changes in the database are actually done by the data adapter.

There are following different types of data providers included in ADO.Net

The .Net Framework data provider for SQL Server - provides access to Microsoft SQL Server.

The .Net Framework data provider for OLE DB - provides access to data sources exposed by using OLE DB.

The .Net Framework data provider for ODBC - provides access to data sources exposed by ODBC.

The .Net Framework data provider for Oracle - provides access to Oracle data source.

The EntityClient provider - enables accessing data through Entity Data Model (EDM) applications.

DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are retrieved from a database. When a connection is established with the database, the data adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection with the database is closed. This is called the 'disconnected architecture'. The dataset works as a virtual database containing tables, rows, and columns.

The following diagram shows the dataset object model −

VB.Net Data Classes

The DataSet class is present in the System.Data namespace. The following table describes all the components of DataSet −

Sr.No. Components & Description
1

It contains all the tables retrieved from the data source.

2

It contains relationships and the links between tables in a data set.

3

It contains additional information, like the SQL statement for retrieving data, time of retrieval, etc.

4

It represents a table in the DataTableCollection of a dataset. It consists of the DataRow and DataColumn objects. The DataTable objects are case-sensitive.

5

It represents a relationship in the DataRelationshipCollection of the dataset. It is used to relate two DataTable objects to each other through the DataColumn objects.

6

It contains all the rows in a DataTable.

7

It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing and navigation.

8

It represents the column that uniquely identifies a row in a DataTable.

9

It represents a row in the DataTable. The DataRow object and its properties and methods are used to retrieve, evaluate, insert, delete, and update values in the DataTable. The NewRow method is used to create a new row and the Add method adds a row to the table.

10

It represents all the columns in a DataTable.

11

It consists of the number of columns that comprise a DataTable.

Connecting to a Database

The .Net Framework provides two types of Connection classes −

SqlConnection − designed for connecting to Microsoft SQL Server.

OleDbConnection − designed for connecting to a wide range of databases, like Microsoft Access and Oracle.

We have a table stored in Microsoft SQL Server, named Customers, in a database named testDB. Please consult 'SQL Server' tutorial for creating databases and database tables in SQL Server.

Let us connect to this database. Take the following steps −

Select TOOLS → Connect to Database

VB.Net Database connection Example

Select a server name and the database name in the Add Connection dialog box.

VB.Net Database Connection

Click on the Test Connection button to check if the connection succeeded.

Connection Success

Add a DataGridView on the form.

VB.Net DataGridView

Click on the Choose Data Source combo box.

Click on the Add Project Data Source link.

Add Project Data Source Link

This opens the Data Source Configuration Wizard.

Select Database as the data source type

Data Source

Choose DataSet as the database model.

Database Model

Choose the connection already set up.

VB.Net Database Connection

Save the connection string.

Saving the connection string

Choose the database object, Customers table in our example, and click the Finish button.

VB.Net database connection

Select the Preview Data link to see the data in the Results grid −

Data Preview

When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −

VB.net data in data grid view

In this example, let us access data in a DataGridView control using code. Take the following steps −

Add a DataGridView control and a button in the form.

Change the text of the button control to 'Fill'.

Double click the button control to add the required code for the Click event of the button, as shown below −

Database Connectivity

Clicking the Fill button displays the table on the data grid view control −

Database connectivity

Creating Table, Columns and Rows

We have discussed that the DataSet components like DataTable, DataColumn and DataRow allow us to create tables, columns and rows, respectively.

The following example demonstrates the concept −

So far, we have used tables and databases already existing in our computer. In this example, we will create a table, add columns, rows and data into it and display the table using a DataGridView object.

Take the following steps −

Add the following code in the code editor.

Example

VB.Net provides support for interoperability between the COM object model of Microsoft Excel 2010 and your application.

To avail this interoperability in your application, you need to import the namespace Microsoft.Office.Interop.Excel in your Windows Form Application.

Creating an Excel Application from VB.Net

Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio: File → New Project → Windows Forms Applications

Finally, select OK, Microsoft Visual Studio creates your project and displays following Form1 .

Insert a Button control Button1 in the form.

Add a reference to Microsoft Excel Object Library to your project. To do this −

Select Add Reference from the Project Menu.

Add Reference

On the COM tab, locate Microsoft Excel Object Library and then click Select.

COM tab

Double click the code window and populate the Click event of Button1, as shown below.

VB.Net Excel Example

Clicking on the Button would display the following excel sheet. You will be asked to save the workbook.

VB.Net Excel Result Form

VB.Net allows sending e-mails from your application. The System.Net.Mail namespace contains classes used for sending e-mails to a Simple Mail Transfer Protocol (SMTP) server for delivery.

The following table lists some of these commonly used classes −

Sr.No. Class & Description
1

Represents an attachment to an e-mail.

2

Stores attachments to be sent as part of an e-mail message.

3

Represents the address of an electronic mail sender or recipient.

4

Stores e-mail addresses that are associated with an e-mail message.

5

Represents an e-mail message that can be sent using the SmtpClient class.

6

Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).

7

Represents the exception that is thrown when the SmtpClient is not able to complete a Send or SendAsync operation.

The SmtpClient Class

The SmtpClient class allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).

Following are some commonly used properties of the SmtpClient class −

Sr.No. Property & Description
1

Specifies which certificates should be used to establish the Secure Sockets Layer (SSL) connection.

2

Gets or sets the credentials used to authenticate the sender.

3

Specifies whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.

4

Gets or sets the name or IP address of the host used for SMTP transactions.

5

Gets or sets the port used for SMTP transactions.

6

Gets or sets a value that specifies the amount of time after which a synchronous Send call times out.

7

Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

Following are some commonly used methods of the SmtpClient class −

Sr.No. Method & Description
1

Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the SmtpClient class.

2

Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, releases all resources used by the current instance of the SmtpClient class, and optionally disposes of the managed resources.

3

Raises the SendCompleted event.

4

Sends the specified message to an SMTP server for delivery.

5

Sends the specified e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects.

6

Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.

7

Sends an e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.

8

Cancels an asynchronous operation to send an e-mail message.

9

Sends the specified message to an SMTP server for delivery as an asynchronous operation.

10

Sends the specified message to an SMTP server for delivery as an asynchronous operation. . The message sender, recipients, subject, and message body are specified using String objects.

11

Returns a string that represents the current object.

The following example demonstrates how to send mail using the SmtpClient class. Following points are to be noted in this respect −

You must specify the SMTP host server that you use to send e-mail. The Host and Port properties will be different for different host server. We will be using gmail server.

You need to give the Credentials for authentication, if required by the SMTP server.

You should also provide the email address of the sender and the e-mail address or addresses of the recipients using the MailMessage.From and MailMessage.To properties, respectively.

You should also specify the message content using the MailMessage.Body property.

In this example, let us create a simple application that would send an e-mail. Take the following steps −

Change the text properties of the labels to - 'From', 'To:' and 'Message:' respectively.

Change the name properties of the texts to txtFrom, txtTo and txtMessage respectively.

Change the text property of the button control to 'Send'

You must provide your gmail address and real password for credentials.

When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window, which you will use to send your e-mails, try it yourself.

Sending Email from VB.Net

The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.

The System.Xml namespace in the .Net Framework contains classes for processing XML documents. Following are some of the commonly used classes in the System.Xml namespace.

Sr.No. Class & Description
1

Represents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.

2

Represents a CDATA section.

3

Provides text manipulation methods that are used by several classes.

4

Represents the content of an XML comment.

5

Encodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types, the values returned are locale independent.

6

Represents the XML declaration node <?xml version='1.0'...?>.

7

Implements a dictionary used to optimize Windows Communication Foundation (WCF)'s XML reader/writer implementations.

8

An abstract class that the Windows Communication Foundation (WCF) derives from XmlReader to do serialization and deserialization.

9

Represents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter to do serialization and deserialization.

10

Represents an XML document.

11

Represents a lightweight object that is useful for tree insert operations.

12

Represents the document type declaration.

13

Represents an element.

14

Represents an entity declaration, such as <!ENTITY... >.

15

Represents an entity reference node.

16

Returns detailed information about the last exception.

17

Defines the context for a set of XmlDocument objects.

18

Gets the node immediately preceding or following this node.

19

Represents a single node in the XML document.

20

Represents an ordered collection of nodes.

21

Represents a reader that provides fast, non-cached forward only access to XML data in an XmlNode.

22

Represents a notation declaration, such as <!NOTATION... >.

23

Provides all the context information required by the XmlReader to parse an XML fragment.

24

Represents a processing instruction, which XML defines to keep processor-specific information in the text of the document.

25

Represents an XML qualified name.

26

Represents a reader that provides fast, noncached, forward-only access to XML data.

27

Specifies a set of features to support on the XmlReader object created by the Create method.

28

Resolves external XML resources named by a Uniform Resource Identifier (URI).

29

Helps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to.

30

Represents white space between markup in a mixed content node or white space within an xml:space= 'preserve' scope. This is also referred to as significant white space.

31

Represents the text content of an element or attribute.

32

Represents a reader that provides fast, non-cached, forward-only access to XML data.

33

Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

34

Resolves external XML resources named by a Uniform Resource Identifier (URI).

35

Represents white space in element content.

36

Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.

37

Specifies a set of features to support on the XmlWriter object created by the XmlWriter.Create method.

XML Parser APIs

The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.

Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory.

Document Object Model (DOM) API − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.

SAX obviously can't process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files.

SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can't use them both for large projects.

For all our XML code examples, let's use a simple XML file movies.xml as an input −

Parsing XML with SAX API

In SAX model, you use the XmlReader and XmlWriter classes to work with the XML data.

The XmlReader class is used to read XML data in a fast, forward-only and non-cached manner. It reads an XML document or a stream.

This example demonstrates reading XML data from the file movies.xml.

Add the movies.xml file in the bin\Debug folder of your application.

Import the System.Xml namespace in Form1.vb file.

Add a label in the form and change its text to 'Movies Galore'.

Add three list boxes and three buttons to show the title, type and description of a movie from the xml file.

Add the following code using the code editor window.

Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the buttons would display, title, type and description of the movies from the file.

VB.Net XML Processing Example 1

The XmlWriter class is used to write XML data into a stream, a file or a TextWriter object. It also works in a forward-only, non-cached manner.

Let us create an XML file by adding some data at runtime. Take the following steps −

Add a WebBrowser control and a button control in the form.

Change the Text property of the button to Show Authors File.

Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author File would display the newly created authors.xml file on the web browser.

VB.Net XML Processing Example 2

Parsing XML with DOM API

According to the Document Object Model (DOM), an XML document consists of nodes and attributes of the nodes. The XmlDocument class is used to implement the XML DOM parser of the .Net Framework. It also allows you to modify an existing XML document by inserting, deleting or updating data in the document.

Following are some of the commonly used methods of the XmlDocument class −

Sr.No. Method Name & Description
1

Adds the specified node to the end of the list of child nodes, of this node.

2

Creates an XmlAttribute with the specified Name.

3

Creates an XmlComment containing the specified data.

4

Creates a default attribute with the specified prefix, local name and namespace URI.

5

Creates an element with the specified name.

6

Creates an XmlNode with the specified node type, Name, and NamespaceURI.

7

Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.

8

Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.

9

Creates an XmlProcessingInstruction with the specified name and data.

10

Creates an XmlSignificantWhitespace node.

11

Creates an XmlText with the specified text.

12

Creates an XmlWhitespace node.

13

Creates an XmlDeclaration node with the specified values.

14

Gets the XmlElement with the specified ID.

15

Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.

16

Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.

17

Inserts the specified node immediately after the specified reference node.

18

Inserts the specified node immediately before the specified reference node.

19

Loads the XML document from the specified stream.

20

Loads the XML document from the specified URL.

21

Loads the XML document from the specified TextReader.

22

Loads the XML document from the specified XmlReader.

23

Loads the XML document from the specified string.

24

Adds the specified node to the beginning of the list of child nodes for this node.

25

Creates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute.

26

Removes all the child nodes and/or attributes of the current node.

27

Removes specified child node.

28

Replaces the child node oldChild with newChild node.

29

Saves the XML document to the specified stream.

30

Saves the XML document to the specified file.

31

Saves the XML document to the specified TextWriter.

32

Saves the XML document to the specified XmlWriter.

In this example, let us insert some new nodes in the xml document authors.xml and then show all the authors' first names in a list box.

Add the authors.xml file in the bin/Debug folder of your application( it should be there if you have tried the last example)

Import the System.Xml namespace

Add a list box and a button control in the form and set the text property of the button control to Show Authors.

Add the following code using the code editor.

Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author button would display the first names of all the authors including the one we have added at runtime.

VB.Net XML Processing Example 3

A dynamic web application consists of either or both of the following two types of programs −

Server-side scripting − these are programs executed on a web server, written using server-side scripting languages like ASP (Active Server Pages) or JSP (Java Server Pages).

Client-side scripting − these are programs executed on the browser, written using scripting languages like JavaScript, VBScript, etc.

ASP.Net is the .Net version of ASP, introduced by Microsoft, for creating dynamic web pages by using server-side scripts. ASP.Net applications are compiled codes written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework.

The ASP.Net application codes could be written in either of the following languages −

Visual Basic .Net

In this chapter, we will give a very brief introduction to writing ASP.Net applications using VB.Net. For detailed discussion, please consult the ASP.Net Tutorial.

ASP.Net Built-in Objects

ASP.Net has some built-in objects that run on a web server. These objects have methods, properties and collections that are used in application development.

The following table lists the ASP.Net built-in objects with a brief description −

Sr.No. Object & Description
1

Describes the methods, properties, and collections of the object that stores information related to the entire Web application, including variables and objects that exist for the lifetime of the application.

You use this object to store and retrieve information to be shared among all users of an application. For example, you can use an Application object to create an e-commerce page.

2

Describes the methods, properties, and collections of the object that stores information related to the HTTP request. This includes forms, cookies, server variables, and certificate data.

You use this object to access the information sent in a request from a browser to the server. For example, you can use a Request object to access information entered by a user in an HTML form.

3

Describes the methods, properties, and collections of the object that stores information related to the server's response. This includes displaying content, manipulating headers, setting locales, and redirecting requests.

You use this object to send information to the browser. For example, you use a Response object to send output from your scripts to a browser.

4

Describes the methods and properties of the object that provides methods for various server tasks. With these methods you can execute code, get error conditions, encode text strings, create objects for use by the Web page, and map physical paths.

You use this object to access various utility functions on the server. For example, you may use the Server object to set a time out for a script.

5

Describes the methods, properties, and collections of the object that stores information related to the user's session, including variables and objects that exist for the lifetime of the session.

You use this object to store and retrieve information about particular user sessions. For example, you can use Session object to keep information about the user and his preference and keep track of pending operations.

ASP.Net Programming Model

ASP.Net provides two types of programming models −

Web Forms − this enables you to create the user interface and the application logic that would be applied to various components of the user interface.

WCF Services − this enables you to remote access some server-side functionalities.

For this chapter, you need to use Visual Studio Web Developer, which is free. The IDE is almost same as you have already used for creating the Windows Applications.

VS Web Developer IDE

Web forms consists of −

User interface

Application logic

User interface consists of static HTML or XML elements and ASP.Net server controls. When you create a web application, HTML or XML elements and server controls are stored in a file with .aspx extension. This file is also called the page file.

The application logic consists of code applied to the user interface elements in the page. You write this code in any of .Net language like, VB.Net, or C#. The following figure shows a Web Form in Design view −

Web Form

Let us create a new web site with a web form, which will show the current date and time, when a user clicks a button. Take the following steps −

Select File → New → Web Site. The New Web Site Dialog Box appears.

Web Form Example

Select the ASP.Net Empty Web Site templates. Type a name for the web site and select a location for saving the files.

You need to add a Default page to the site. Right click the web site name in the Solution Explorer and select Add New Item option from the context menu. The Add New Item dialog box is displayed −

Web Form Example

Select Web Form option and provide a name for the default page. We have kept it as Default.aspx. Click the Add button.

The Default page is shown in Source view

Web Form Example

Set the title for the Default web page by adding a value to the <Title> tag of the page, in the Source view −

To add controls on the web page, go to the design view. Add three labels, a text box and a button on the form.

Web Form Example

Double-click the button and add the following code to the Click event of the button −

When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, the following page opens in the browser −

Web Form Example

Enter your name and click on the Submit button −

Web Form Example

Web Services

A web service is a web application, which is basically a class consisting of methods that could be used by other applications. It also follows a code-behind architecture like the ASP.Net web pages, although it does not have an user interface.

The previous versions of .Net Framework used this concept of ASP.Net Web Service, which had .asmx file extension. However, from .Net Framework 4.0 onwards, the Windows Communication Foundation (WCF) technology has evolved as the new successor of Web Services, .Net Remoting and some other related technologies. It has rather clubbed all these technologies together. In the next section, we will provide a brief introduction to Windows Communication Foundation(WCF).

If you are using previous versions of .Net Framework, you can still create traditional web services. Please consult ASP.Net - Web Services tutorial for detailed description.

Windows Communication Foundation

Windows Communication Foundation or WCF provides an API for creating distributed service-oriented applications, known as WCF Services.

Like Web services, WCF services also enable communication between applications. However, unlike web services, the communication here is not limited to HTTP only. WCF can be configured to be used over HTTP, TCP, IPC, and Message Queues. Another strong point in favour of WCF is, it provides support for duplex communication, whereas with web services we could achieve simplex communication only.

From beginners' point of view, writing a WCF service is not altogether so different from writing a Web Service. To keep the things simple, we will see how to −

Create a WCF Service

Create a Service Contract and define the operations

Implement the contract

Test the Service

Utilize the Service

To understand the concept let us create a simplistic service that will provide stock price information. The clients can query about the name and price of a stock based on the stock symbol. To keep this example simple, the values are hardcoded in a two-dimensional array. This service will have two methods −

GetPrice Method − it will return the price of a stock, based on the symbol provided.

GetName Method − it will return the name of the stock, based on the symbol provided.

Creating a WCF Service

Open VS Express for Web 2012

Select New Web Site to open the New Web Site dialog box.

Select WCF Service template from list of templates −

Creating a WCF Service

Select File System from the Web location drop-down list.

Provide a name and location for the WCF Service and click OK.

A new WCF Service is created.

Creating a Service Contract and Defining the Operations

A service contract defines the operation that a service performs. In the WCF Service application, you will find two files automatically created in the App_Code folder in the Solution Explorer

IService.vb − this will have the service contract; in simpler words, it will have the interface for the service, with the definitions of methods the service will provide, which you will implement in your service.

Service.vb − this will implement the service contract.

WCF Service Example

Replace the code of the IService.vb file with the given code −

Implementing the Contract

In the Service.vb file, you will find a class named Service which will implement the Service Contract defined in the IService interface.

Replace the code of IService.vb with the following code −

Testing the Service

To run the WCF Service, so created, select the Debug → Start Debugging option from the menu bar. The output would be −

WCF Service Testing

For testing the service operations, double click the name of the operation from the tree on the left pane. A new tab will appear on the right pane.

Enter the value of parameters in the Request area of the right pane and click the 'Invoke' button.

The following diagram displays the result of testing the GetPrice operation −

WCF Service Testing

The following diagram displays the result of testing the GetName operation −

WCF Service Testing

Utilizing the Service

Let us add a default page, a ASP.NET web form in the same solution from which we will be using the WCF Service we have just created.

Right click on the solution name in the Solution Explorer and add a new web form to the solution. It will be named Default.aspx.

Add two labels, a text box and a button on the form.

WCF Service Utilization

We need to add a service reference to the WCF service we just created. Right click the website in the Solution Explorer and select Add Service Reference option. This opens the Add Service Reference Dialog box.

Enter the URL(location) of the Service in the Address text box and click the Go button. It creates a service reference with the default name ServiceReference1 . Click the OK button.

Add Service Reference

Adding the reference does two jobs for your project −

Creates the Address and Binding for the service in the web.config file.

Creates a proxy class to access the service.

Double click the Get Price button in the form, to enter the following code snippet on its Click event −

WCF Service Utilization

Enter a symbol and click the Get Price button to get the hard-coded price −

WCF Service Utilization

IMAGES

  1. VB.NET : The Easy Way : How to Connect to SQL Server Database File

    vb net database assignment

  2. VB.Net Part-3: How to create Database & users table for registration in vb.net

    vb net database assignment

  3. Visual Basic.net: Create a sql server database and tables programmatically using vb.net

    vb net database assignment

  4. create a new database Mysql in VB.net

    vb net database assignment

  5. VB Net Database Tutorial Series -2. create a simple database in MS Access

    vb net database assignment

  6. VB.NET MS Access Database Tutorial 4 # How to use Chart /Graph with local database in VB.NET

    vb net database assignment

VIDEO

  1. VB.Net Database Tutorial Series -4. connect database in our program

  2. how to program Asset Register in VB.net Visual studio 2013/2019

  3. Creating Sub Procedures in VB NET 2012

  4. VB.Net Database Tutorial Series-3. Database controls in vb.net

  5. Enrollment and Billing System in VB NET and MySQL Database DEMO

  6. Creating setup file with database, in vb.net in hindi

COMMENTS

  1. VB.Net

    ds = CreateDataSet() DataGridView1.DataSource = ds.Tables("Student") End Sub End Class. VB.Net - Database Access - Applications communicate with a database, firstly, to retrieve the data stored there and present it in a user-friendly way, and secondly, to update the database by inserting, modifying and deleting data.

  2. code-warrior/assignment-1--databases--cs-365--fall-2024

    In this assignment, you'll work in two languages: XML and JSON; one will mirror the other. For the XML part, you'll create an XML document that represents students at a university, and you'll author a grammar, via a DTD document, that will define the language of your XML document.

  3. vb.net

    Using cnn As OleDbConnection = New OleDbConnection(connectionString) cnn.Open() ' open the connection. Using cmd As New OleDbCommand(sqlCommand, cnn) ' make a command object. dr = cmd.ExecuteReader() ' execute the reader. dt.Load(dr) ' BAM - get all the data into the DataTable at once. End Using ' close everything up.

  4. Create database, add tables in .NET Framework apps

    The Data Source Configuration Wizard opens.. On the Choose a Data Source Type page, choose Database and then choose Next.. On the Choose a Database Model page, choose Next to accept the default (Dataset).. On the Choose Your Data Connection page, select the SampleDatabase.mdf file in the dropdown list, and then choose Next.. On the Save the Connection String to the Application Configuration ...

  5. VB.NET

    To create a database, let's open the SQL Server Object Explorer, expand the SQL Server and right-click on the Databases and select the Add New Database. It will open the Create Database dialog. Enter the database name such as MyTestDb and click the Ok button. Now right-click on the newly created database and select New Query...

  6. Ch 25

    Databases with VB.NET This chapter explains: the nature of simple databases and the SQL language; ... Assignment 182 : Media Ltd : 34.6 : The Trees : United Co: 3.72 : Note that: ... Database Manipulation. Figure 25.1 shows the form, and here is the code:

  7. VB.NET SQL Examples for Querying Databases Efficiently

    The command you used to create the VB.NET project created a file named Program.vb. Open this file and update it as follows: DatabaseInitializer.InitializeDb() Run this program and you should see it create a file named mydatabase.db. This is the simple database that you will use in the following examples.

  8. Lesson 23 Creating a Database Application

    In the following example, we will create a simple database application which enables one to browse customers' names. To create this application, select the data control on the toolbox (as shown in Figure 23.1) and insert it into the new form. Place the data control somewhere at the bottom of the form. Name the data control as data_navigator.

  9. Insert records into database (.NET Framework)

    The following procedure demonstrates how to insert new records into a database by using the TableAdapter.Update method: Add new records to the desired DataTable by creating a new DataRow and adding it to the Rows collection. After you add the new rows to the DataTable, call the TableAdapter.Update method.

  10. Create a simple data application by using ADO.NET

    Create the sample database by following these steps: In Visual Studio, open the Server Explorer window. Right-click on Data Connections and choose Create New SQL Server Database. In the Server name text box, enter (localdb)\mssqllocaldb. In the New database name text box, enter Sales, then choose OK. The empty Sales database is created and ...

  11. vb.net

    1. Already have the DataTable populated but need to dump its entire table contents into an Access database. If conn.State <> ConnectionState.Open Then conn.Open() Dim adapter As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM " & sMdbTableName, conn) adapter.InsertCommand = New OleDbCommand("INSERT INTO " & sMdbTableName & " SELECT ...

  12. How to Connect Access Database in VB.Net

    Steps How to Connect Access Database in VB.Net. Step 1: Create an MS Access Database. Open an MS Access Database on your Computer and Create a Blank Database and Save it as "inventorydb.accdb". Step 2: Create a Database Table. To create a table, follow the image below and save it as "tblitems".

  13. 25+ VB.Net Project Topics For Beginners to Advanced Developers

    Here's a step-by-step guide on how to create a setup for a VB.NET project using Visual Studio: Open your VB.NET project in Visual Studio. Navigate to the "Build" menu and select "Publish <YourProjectName>". In the Publish Wizard, choose the publishing location, such as a folder, FTP server, or Azure App Service.

  14. Assignment 3

    VB.NET Code for Sakila database assignment assignment cover page course: assignment: bis 425 assignment please click on the blue text to fill in the. Skip to document. University; ... Assignment 3 - VB.NET Code for Sakila database. Course: Information Systems Development Project (BIS 425) 6 Documents.

  15. VB.NET simple Database Assignment

    VB.NET simple Database Assignment. urvishjain. 3 New Member. Hi People i'm working with small assignment where i have to create a backup of my access database ([filename].mdb) in a word file/ Exel spreadsheet so that later i can retrieve back that to a mdb file..... Please help me out!!! :confused:

  16. VB.Net

    There are following assignment operators supported by VB.Net −. Operator. Description. Example. =. Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C. +=. Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand.

  17. 124aris/VB.NET-Assignment-2

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. master

  18. Open SQL database by VB .NET

    In the Data Link Properties dialog box, click localhost in the Select or enter a server name box. Click Windows NT Integrated Security to log on to the server. Click Select the database on the server, and then select Northwind database from the list. Click Test Connection to validate the connection, and then click OK.

  19. PDF The Handa Library of The University of Cambodia

    The Handa Library of The University of Cambodia - UC

  20. vb.net

    The assignment is as follows: StudentScores. Develop an application that reads in student names (limited to 20 students) and scores (up to 6 per student) from a tab delimited file, StudentScores.txt (in Student Files). ... Help with using an array to insert items into a textbox vb.net. 3. Writing Variables to a Pre-existing Array in VB.Net. 0 ...

  21. VB.Net

    Advertisements. VB.Net - Quick Guide - Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented on the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not backwards-compatible with VB6, and any code written in the old version does not compile under VB.NET.