Advanced Study Material for Computer Science: .NET Technology
Explore structured advanced study materials through the Application of .NET Technology Unit 07 File and Database Applications Notes Set 02. Tailored for learners, utilizing these Computer Science resources ensures thorough preparation and strengthens foundational knowledge before final evaluations.
Practice Computer Science Resources: .NET Technology
Access the complete useful resource PDF for Computer Science below. Regular practice with these targeted academic notes builds familiarity with complex topics and helps secure higher marks in final school evaluations.
This page covers structured exception handling with Try, Catch, Finally and Throw, user-defined exceptions, and the building of menus and context menus in Windows forms. It then introduces ADO.Net: data providers, DataSet, connecting to a SQL Server database, filling a DataGridView and automating Excel from VB.Net.
Exception Handling
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.
An exception is an object instance of the Framework Class Library (FCL) supplied Exception class or one of its subclasses. It is used by VB .NET to notify you of:
1. Errors
2. Problems
3. Other unusual conditions that may occur while your system is running.
Causing an Exception
1. Create deliberate error.
2. Exception is thrown.
3. Message dialog indicates that code did not deal with exception.
4. Execution is interrupted.
Error Handling
Try: A Try block identifies a block of code for which particular exceptions will be activated. It is 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.
Every exception will execute at least three of the statements once the error occurs.
Syntax
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. To raise an exception, a method catches an exception using a combination of the Try and Catch keywords.
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End TryException 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.
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. The following example demonstrates handling of a division by zero:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End ModuleCreating 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:
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End ModuleThrowing Objects
You can use a throw statement in the catch block to throw the present object as:
Throw [ expression ]
You can throw an object if it is either directly or indirectly derived from the System.Exception class. The following example throws an ApplicationException object:
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End ModuleException class hierarchy
The diagram shows the class hierarchy of exception class.
Exception
|-- ApplicationException
| |-- (user-defined exception classes)
|-- SystemException
|-- ArgumentException
| |-- ArgumentOutOfRangeException
|-- ArithmeticException
| |-- DivideByZeroException
|-- IndexOutOfRangeExceptionIt is commonly divided into two types of exceptions:
1. Application exception.
2. System exception.
Creating Context Menus
1. Shortcut menus that pop up when you right-click.
2. Are specific to the component to which user is pointing, reflecting options available for that component or situation.
3. A context menu does not have a top level menu.
4. Application can have multiple context menus.
5. Add ContextMenu component to the form.
6. Appears in the Component Tray.
7. Click on the words "Context Menu", at the top of the form, the words "Type Here" appear.
8. Click on the words "Type Here" and proceed as you did for the main menu.
Menu
A menu is used to do multiple operations at output stage. The MenuStrip control has the following properties:
| S.N | Property | Description |
|---|---|---|
| 1 | CanOverflow | Gets or sets a value indicating whether the MenuStrip supports overflow functionality. |
| 2 | GripStyle | Gets or sets the visibility of the grip used to reposition the control. |
| 3 | MdiWindowListItem | Gets or sets the ToolStripMenuItem that is used to display a list of Multiple-document interface (MDI) child forms. |
| 4 | ShowItemToolTips | Gets or sets a value indicating whether ToolTips are shown for the MenuStrip. |
| 5 | Stretch | Gets or sets a value indicating whether the MenuStrip stretches from end to end in its container. |
Menu Bar
1. Contains menus which drop down to display list of menu items.
2. Each item has a name and text property.
3. Each item has a click event.
4. Add MainMenu control to form.
5. Appears in the Component Tray, below form, where nondisplay controls are shown.
6. Words "Type Here" appear at the top of the form.
Defining Menus
1. To create the menus simply type where the words "Type Here" appear at the top of the form.
2. Include & symbol as you type to indicate keyboard access keys.
3. You are actually entering the Text property for a MenuItem object.
4. Change MenuItem object names in the Properties window and follow consistent naming conventions.
Submenus
1. Pop up to the right of a menu item.
2. Filled triangle to the right of the menu item indicates to the user the existence of a submenu.
3. Create submenus by moving to the right of a menu item and typing the next item's text.
Separator Bars
Separator bars are used for grouping menu items according to their purpose and are visually represented as a bar across the menu. Create using one of two methods:
1. Typing a single hyphen for the text.
2. Right-click on Menu Designer where you want a separator bar and choose Insert Separator.
Coding for Menu Items
1. Double-click any menu item to open the item's click event procedure.
2. Write code for the click event procedure.
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles ExitToolStripMenuItem.Click
End
End SubModifying Menu Items
Right-click the Menu Bar to:
1. Delete.
2. Insert New.
3. Insert Separator.
4. Edit Names.
This displays the menu item Name property rather than the Text property on the form. You can also drag and drop menu items to new locations.
Menu Properties
1. Enabled property, True/False.
2. Checked property, True/False. Used to indicate current state of menu item that can be turned on and off.
3. Create keyboard shortcuts: in Properties window for menu item, select the Shortcut property and make a choice from drop-down list.
Standards for Windows Menus
1. Follow Windows standards for applications.
2. Include keyboard access keys.
3. Use standards for shortcut keys, if used.
4. Place File menu at left end of menu bar and end File menu with Exit.
5. Help, if included, is placed at right end of menu bar.
Database Connection
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 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:
| S.N | Object | Description |
|---|---|---|
| 1 | Connection | This component is used to set up a connection with a data source. |
| 2 | Command | A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data source. |
| 3 | DataReader | Data reader is used to retrieve data from a data source in a read-only mode. |
| 4 | DataAdapter | 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:
1. The .Net Framework data provider for SQL Server: Provides access to Microsoft SQL Server.
2. The .Net Framework data provider for OLE DB: Provides access to data sources exposed by using OLE DB.
3. The .Net Framework data provider for ODBC: Provides access to data sources exposed by ODBC.
4. The .Net Framework data provider for Oracle: Provides access to Oracle data source.
5. The EntityClient provider: Enables accessing data through Entity Data Model (EDM) applications.
DataSet
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 DataSet class is present in the System.Data namespace.
| Component | Description |
|---|---|
| DataTableCollection | It contains all the tables retrieved from the data source. |
| DataRelationCollection | It contains relationships and the links between tables in a data set. |
| ExtendedProperties | It contains additional information, like the SQL statement for retrieving data, time of retrieval, etc. |
| DataTable | It represents a table in the DataTableCollection of a dataset. It consists of the DataRow and DataColumn objects. The DataTable objects are case-sensitive. |
| DataRelation | 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. |
| DataRowCollection | It contains all the rows in a DataTable. |
| DataView | It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing and navigation. |
| PrimaryKey | It represents the column that uniquely identifies a row in a DataTable. |
| DataRow | 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. |
| DataColumnCollection | It represents all the columns in a DataTable. |
| DataColumn | It consists of the number of columns that comprise a DataTable. |
Connecting to a Database
The .Net Framework provides two types of Connection classes:
1. SqlConnection - designed for connecting to Microsoft SQL Server.
2. OleDbConnection - designed for connecting to a wide range of databases, like Microsoft Access and Oracle.
Suppose we have a table stored in Microsoft SQL Server, named Customers, in a database named testDB. Please consult a SQL Server tutorial for creating databases and database tables in SQL Server. Let us connect to this database. Take the following steps:
1. Select TOOLS, Connect to Database.
2. Select a server name and the database name in the Add Connection dialog box.
3. Click on the Test Connection button to check if the connection succeeded.
4. Add a DataGridView on the form.
5. Click on the Choose Data Source combo box.
6. Click on the Add Project Data Source link.
7. This opens the Data Source Configuration Wizard.
8. Select Database as the data source type.
9. Choose DataSet as the database model.
10. Choose the connection already set up.
11. Save the connection string.
12. Choose the database object, Customers table in our example, and click the Finish button.
13. Select the Preview Data link to see the data in the Results grid.
When the application is run using the Start button available at the Visual Studio tool bar, the Customers table is shown in the data grid view on the form.
In this example, let us access data in a DataGridView control using code. Take the following steps:
1. Add a DataGridView control and a button in the form.
2. Change the text of the button control to 'Fill'.
3. Double click the button control to add the required code for the Click event of the button, as shown:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS' table.
'You can move, or remove it, as needed.
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "Customers"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Dim connection As SqlConnection = New SqlConnection()
connection.ConnectionString = "Data Source=KABIR-DESKTOP;Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("select * from Customers", connection)
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
End Sub
End ClassClicking the Fill button displays the table on the data grid view control (columns ID, NAME, AGE, ADDRESS and SALARY).
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:
1. Add a DataGridView control and a button in the form.
2. Change the text of the button control to 'Fill'.
3. Add the following code in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "Students"
End Sub
Private Function CreateDataSet() As DataSet
'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function
Private Function CreateStudentTable() As DataTable
Dim Students As DataTable
Students = New DataTable("Student")
'adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
'adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function
Private Sub AddNewColumn(ByRef table As DataTable, _
ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub
'adding data into the table
Private Sub AddNewRow(ByRef table As DataTable, _
ByRef id As Integer, _
ByRef name As String, ByRef city As String)
Dim newrow As DataRow = table.NewRow()
newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
End Sub
End ClassClicking the Fill button displays the table on the data grid view control, with the columns StudentID, StudentName and StudentCity.
Creating an Excel Application from VB.Net
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. Let's start with creating a Windows Forms Application by following these steps in Microsoft Visual Studio:
1. File, New Project, Windows Forms Applications.
2. Finally, select OK, Microsoft Visual Studio creates your project and displays Form1.
3. Insert a Button control Button1 in the form.
4. Add a reference to Microsoft Excel Object Library to your project.
5. Select Add Reference from the Project Menu.
6. On the COM tab, locate Microsoft Excel Object Library and then click Select.
7. Click OK.
8. Double click the code window and populate the Click event of Button1, as shown:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
' Start Excel and get Application object.
appXL = CreateObject("Excel.Application")
appXL.Visible = True
' Add a new workbook.
wbXl = appXL.Workbooks.Add
shXL = wbXl.ActiveSheet
' Add table headers going cell by cell.
shXL.Cells(1, 1).Value = "First Name"
shXL.Cells(1, 2).Value = "Last Name"
shXL.Cells(1, 3).Value = "Full Name"
shXL.Cells(1, 4).Value = "Specialization"
' Format A1:D1 as bold, vertical alignment = center.
With shXL.Range("A1", "D1")
.Font.Bold = True
.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
End With
' Create an array to set multiple values at once.
Dim students(5, 2) As String
students(0, 0) = "Zara"
students(0, 1) = "Ali"
students(1, 0) = "Nuha"
students(1, 1) = "Ali"
students(2, 0) = "Arilia"
students(2, 1) = "RamKumar"
students(3, 0) = "Rita"
students(3, 1) = "Jones"
students(4, 0) = "Umme"
students(4, 1) = "Ayman"
' Fill A2:B6 with an array of values (First and Last Names).
shXL.Range("A2", "B6").Value = students
' Fill C2:C6 with a relative formula (=A2 & " " & B2).
raXL = shXL.Range("C2", "C6")
raXL.Formula = "=A2 & "" "" & B2"
' Fill D2:D6 values.
With shXL
.Cells(2, 4).Value = "Biology"
.Cells(3, 4).Value = "Mathematics"
.Cells(4, 4).Value = "Physics"
.Cells(5, 4).Value = "Mathematics"
.Cells(6, 4).Value = "Arabic"
End With
' AutoFit columns A:D.
raXL = shXL.Range("A1", "D1")
raXL.EntireColumn.AutoFit()
' Make sure Excel is visible and give the user control
' of Excel's lifetime.
appXL.Visible = True
appXL.UserControl = True
' Release object references.
raXL = Nothing
shXL = Nothing
wbXl = Nothing
appXL.Quit()
appXL = Nothing
Exit Sub
Err_Handler:
MsgBox(Err.Description, vbCritical, "Error: " & Err.Number)
End Sub
End ClassWhen the code is executed and run using the Start button available at the Visual Studio tool bar, a form with a button appears. Clicking on the button displays an Excel sheet with the columns First Name, Last Name, Full Name and Specialization filled for five students, and you will be asked to save the workbook.
Free study material for Computer Science
Useful Resources and Notes for Computer Science .NET Technology
Essential Notes for Computer Science
Explore essential learning tools for Computer Science .NET Technology. This curated collection features in-depth notes and targeted practice questions built around the active 2026 curriculum to streamline your daily revision.
Verified Solutions for Computer Science
Built using official NCERT guidelines for Computer Science, these materials provide reliable academic support. Integrating past examination questions and step-by-step solutions helps students understand official CBSE grading criteria.
Enhance Accuracy with Online Tests
Wrap up your chapter revision by testing your knowledge against standard objective question formats. Explore our full library of free, up-to-date sample papers and online assessments to secure top grades in your CBSE examinations.
FAQs
The latest 2026-27 advanced study resources for Computer Science are available for free on StudiesToday.com which includes NCERT Exemplars, high-order thinking skills (HOTS) questions, and deep-dive concept summaries.
Our exhaustive Computer Science package includes chapter wise revision notes, solved practice sheets, important formulas and Concept Maps to help in better understanding of all topics.
Yes. For , our resources have been developed to help you get better marks in school exams and also build fundamental strength needed for entrance tests including Competency Based learning.
in , students should use Active Recall method, read the concept summary, then solve the Important Questions section without looking at the answers and then check your answers.
All Computer Science study materials are provided in mobile-friendly PDF. You can download and save them on your device.
Yes, our team has ensured that all Computer Science materials for are strictly aligned with the National Education Policy (NEP) 2020 and the latest 2026-27 syllabus.