Tutorial
Tutorial
Click Dim connetionString As String Dim cnn As OdbcConnection connetionString = "Driver={Microsoft Access Driver (*.mdb)};DBQ=yourdatabasename.mdb;" cnn = New OdbcConnection(connetionString) Try cnn.Open() MsgBox("Connection Open ! ") cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
You have to provide the necessary informations to the Connection String. connetionString = "Driver = {Microsoft Access Driver (*.mdb)}; DBQ = yourdatabasename.mdb;"
ADO.NET Command
The Command Object in ADO.NET executes SQL statements and Stored Procedures against the data source specified in the Connection Object. The Command Object required an instance of a Connection Object for executing the SQL statements. That is, for retrieving data or execute an SQL statement against a Data Source , you have to create a Connection Object and open a connection to the Data Source, and assign the open connection to the connection property of the Command Object. When the Command Object return result set , a Data Reader is used to retrieve the result set.
The Command Object has a property called CommandText, which contains a String value that represents the command that will be executed in the Data Source. When the CommandType property is set to StoredProcedure, the CommandText property should be set to the name of the stored procedure.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(Sql, cnn) cmd.ExecuteNonQuery() cmd.Dispose() cnn.Close() MsgBox(" ExecuteNonQuery in SqlCommand executed !!") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here"
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose() cnn.Close() MsgBox(" No. of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here like Select Count(*) from product"
The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results from the Data Source, which do not update the data. The SqlDataReader cannot be created directly from code, they created only by calling the ExecuteReader method of a Command Object. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim sql As String Dim reader As SqlDataReader connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" cnn = New SqlConnection(connetionString) Try cnn.Open() cmd = New SqlCommand(sql, cnn) reader = cmd.ExecuteReader() While reader.Read() MsgBox(reader.Item(0) & " - " & reader.Item(1) & " reader.Item(2)) End While reader.Close() cmd.Dispose() cnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
" &
connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password" sql = "Your SQL Statement Here , like Select * from product"
DataReader = Command.ExecuteReader() DataReader Object provides a connection oriented data access to the data Sources. A Connection Object can contain only one DataReader at a time and the connection in the DataReader remains open and cannot be used for any other purpose while data is being accessed. When started to read from a DataReader it should always be open and positioned prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist . DataReader.Raed() There are two types of DataReader in ADO.NET. They are SqlDataReader and the OleDbDataReader. The System.Data.SqlClient and System.Data.OleDb are containing these DataReaders respectively. From the following link you can see in details about these classes.
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & " " & sqlReader.Item(2)) End While sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here , like Select * from product"
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from orderdetails" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() While sqlReader.Read() MsgBox("From first SQL - " & sqlReader.Item(0) & " sqlReader.Item(1)) End While sqlReader.NextResult() While sqlReader.Read() MsgBox("From second SQL sqlReader.Item(1)) End While sqlReader.NextResult() While sqlReader.Read() MsgBox("From third SQL sqlReader.Item(1)) End While " & sqlReader.Item(0) & " " & " & sqlReader.Item(0) & " " &
" &
sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from orderdetails"
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader() Dim schemaTable As DataTable = sqlReader.GetSchemaTable() Dim row As DataRow Dim column As DataColumn For Each row In schemaTable.Rows For Each column In schemaTable.Columns MsgBox(String.Format("{0} = {1}", column.ColumnName, row(column))) Next Next sqlReader.Close() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
What is DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the communication between the Dataset and the Datasource. We can use the DataAdapter in combination with the DataSet Object. That is these two objects combine to enable both data access and data manipulation capabilities.
The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data Source. The Insert , Update and Delete SQL operations , we are using the continuation of the Select command perform by the DataAdapter. That is the DataAdapter uses the Select statements to fill a DataSet and use the other three SQL commands (Insert, Update, delete) to transmit changes back to the Database. From the following links describe how to use SqlDataAdapter and OleDbDataAdapter in detail.
What is SqlDataAdapter
SqlDataAdapter is a part of the ADO.NET Data Provider and it resides in the System.Data.SqlClient namespace. SqlDataAdapter provides the communication between the Dataset and the SQL database. We can use SqlDataAdapter Object in combination with Dataset Object. Dim adapter As New SqlDataAdapter The SqlDataAdapter Object and DataSet objects are combine to perform both data access and data manipulation operations in the SQL Server Database. When the user perform the SQL operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly affect the Database, until the user invoke the Update method in the SqlDataAdapter. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click Dim connetionString As String Dim sqlCnn As SqlConnection Dim sqlCmd As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserNamePassword=Password" sql = "Select * from product" sqlCnn = New SqlConnection(connetionString) Try sqlCnn.Open() sqlCmd = New SqlCommand(sql, sqlCnn) adapter.SelectCommand = sqlCmd adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " ds.Tables(0).Rows(i).Item(1)) Next adapter.Dispose() sqlCmd.Dispose() sqlCnn.Close() Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
--
" &
ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
Dim retValue As Integer Command = New SqlCommand(Sql, Connection) retValue = Command.ExecuteNonQuery()
The above code create a procedure named as 'SPPUBLISHER' and it execute SQL statement that select all publisher name from publishers table from the PUB database. Using stored procedures, database operations can be encapsulated in a single command, optimized for best performance, and enhanced with additional security. To call a stored procedure from VB.NET application, set the CommandType of the Command object to StoredProcedure.
command.CommandType = CommandType.StoredProcedure
From the following source code you can see how to call a stored procedure from VB.NET application. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim command As New SqlCommand Dim ds As New DataSet
Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPPUBLISHER" adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class
The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure param = New SqlParameter("@COUNTRY", "Germany") param.Direction = ParameterDirection.Input param.DbType = DbType.String
command.Parameters.Add(param)
The above code passing country parameter to the stored procedure from vb.net. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim command As New SqlCommand Dim param As SqlParameter Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword" connection = New SqlConnection(connetionString) connection.Open() command.Connection = connection command.CommandType = CommandType.StoredProcedure command.CommandText = "SPCOUNTRY" param = New SqlParameter("@COUNTRY", "Germany") param.Direction = ParameterDirection.Input param.DbType = DbType.String command.Parameters.Add(param) adapter = New SqlDataAdapter(command) adapter.Fill(ds) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0)) Next connection.Close() End Sub End Class
The following example you can see how it happen. 1. Dim iDbl As Double 2. Dim iInt As Integer 3. iDbl = 9.123 4. MsgBox("The value of iDbl is " iDbl) 5. iInt = iDbl 6. MsgBox("The value of iInt is " iInt) line no 1 : Declare a Double datatype variable iDble line no 2 : Declare an Integer datatyoe variable iInt line no 3 : Assign a decimal value to iDbl line no 4 : Display the value of iDbl line no 5 : Assign the value of iDbl to iInt line no 6 : Display the value of iInt The first messagebox display the value of iDbl is 9.123 The second messegebox display the value od iInt is 9 iInt display only 9 because the value is narrowed to 9 to fit in an Integer variable. Here the Compiler made the conversion for us. These type fo conversions are called Implicit Conversion . The Implicit Conversion perform only when the Option Strict switch is OFF Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim iDbl As Double Dim iInt As Integer iDbl = 9.123 MsgBox("The value of iDbl is " & iDbl) iInt = iDbl
'after conversion MsgBox("The value of iInt is " & iInt) End Sub End Class
Explicit Type Conversions In some cases we have to perform conversions , that is the compiler does not automatically convert a type to another . These type of conversion is called Explicit conversion . An explicit conversion uses a type conversion keyword. With these conversion keywords we hav to perform the Explicit Conversion.
Finally The code in the finally block will execute even if there is no Exceptions. That means if you write a finally block , the code should execute after the execution of try block or catch block.
Try code exit from Try Catch [Exception [As Type]] code - if the exception occurred this code will execute exit Catch Finally code - this code should execute , if exception occurred or not
From the following VB.NET code , you can understand how to use try..catch statements. Here we are going to divide a number by zero . Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try
Dim i As Integer Dim resultValue As Integer i = 100 resultValue = i / 0 MsgBox("The result is " & resultValue) Catch ex As Exception MsgBox("Exception catch here ..") Finally MsgBox("Finally block executed ") End Try End Sub End Class
When you execute this program you will "Exception catch here .." first and then "Finally block executed " . That is when you execute this code , an exception happen and it will go to catch block and then it will go to finally block.
The above program , declare a String variable and assigned a value in it and it displays. Take a look at the following program , it is an example of Option Explicit Of Download Source Code Print Source Code
Option Explicit Off Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click someVariable = "Option Explicit ON" MsgBox(someVariable) End Sub End Class
Here "someVariable" is not declared , because the Option Explicit Of , without any compiler error you can continue the program.
The above program is a normal vb.net program and is in default Option Strict Off . Because its Option Strict Off we can convert the value of Long to an Integer. Take a look at the following program. Download Source Code Print Source Code
Option Strict On Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim longNum As Long Dim intNum As Integer longNum = 12345 intNum = longNum MsgBox(intNum) End Sub End Class
When you write this source code the compiler will shows the message "Option Strict On disallows implicit conversions from 'Long' to 'Integer'" The compiler generate error because in the program we put "Option Strict On" and prevent the program from automatic conversion.
Dim num As Integer num = 100 result = num / 0 MsgBox("here") End Sub End Class
when u execute this program you will get error message like " Arithmetic operation resulted in an overflow " See the program we put an On Error GoTo statement Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click On Error GoTo nextstep Dim result As Integer Dim num As Integer num = 100 result = num / 0 nextstep: MsgBox("Control Here") End Sub End Class
When you execute the program you will get the message box "Control Here" . Because the On Error statement redirect the exception to the Label statement.
Label Control
Microsoft Visual Studio .NET controls are the graphical tools you use to build the user interface of a VB.Net program. Labels are one of the most frequently used Visual Basic control. A Label control lets you place descriptive text , where the text does not need to be changed by the user. The Label class is defined in the System.Windows.Forms namespace.
Add a Label control to the form. Click Label in the Toolbox and drag it over the forms Designer and drop it in the desired location.
If you want to change the display text of the Label, you have to set a new text to the Text property of Label.
Label1.Text = "This is my first Label"
You can load Image in Label control , if you want to load an Image in the Lable control you can code like this
Label1.Image = Image.FromFile("C:\testimage.jpg")
The following source code shows how to set some properties of the Label through coding. Download Source Code Print Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Label1.Text = "This is my first Label" Label1.BorderStyle = BorderStyle.FixedSingle Label1.TextAlign = ContentAlignment.MiddleCenter End Sub
Button Control
Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client side Windows applications. A Button is a control, which is an interactive component that enables users to communicate with an application which we click and release to perform some actions.
The Button control represents a standard button that reacts to a Click event. A Button can be clicked by using the mouse, ENTER key, or SPACEBAR if the button has focus. When you want to change display text of the Button , you can change the Text property of the button.
Button1.Text = "My first Button"
Similarly if you want to load an Image to a Button control , you can code like this
Button1.Image = Image.FromFile("C:\testimage.jpg")
The following vb.net source code shows how to change the button Text property while Form loading event and to display a message box when pressing a Button Control. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Button1.Text = "Click Here" End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MsgBox("http://vb.net-informations.com") End Sub End Class
TextBox Control
VB.Net provides several mechanisms for gathering input in a program. A TextBox control is used to display, or accept as input, a single line of text.
VB.Net programmers make extensive use of the TextBox control to let the user view or enter large amount of text. A text box object is used to display text on a form or to get user input while a VB.Net program is running. In a text box, a user can type data or paste it into the control from the clipboard. For displaying a text in a TextBox control , you can code like this
TextBox1.Text = "http://vb.net-informations.com"
You can also collect the input value from a TextBox control to a variable like this way
Dim var As String var = TextBox1.Text
when a program wants to prevent a user from changing the text that appears in a text box, the program can set the controls Readonly property is to True.
TextBox1.ReadOnly = True
By default TextBox accept single line of characters , If you need to enter more than one line in a TextBox control, you should change the Multiline property is to True.
TextBox1.Multiline = True
Sometimes you want a textbox to receive password from the user. In order to keep the password confidential, you can set the PasswordChar property of a textbox to a specific character.
TextBox1.PasswordChar = "*"
The above code set the PasswordChar to * , so when the user enter password then it display only * instead of other characters. From the following VB.Net source code you can see some important property settings to a TextBox control. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Width = 200 TextBox1.Height = 50 TextBox1.Multiline = True End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As String var = TextBox1.Text MsgBox(var) End Sub End Class
ComboBox Control
VB.Net controls are located in the Toolbox of the development environment, and you use them to create objects on a form with a simple series of mouse clicks and dragging motions. The ComboBox control , which lets the user choose one of several choices.
The user can type a value in the text field or click the button to display a drop down list. In addition to display and selection functionality, the ComboBox also provides features that enable you to efficiently add items to the ComboBox.
ComboBox1.Items.Add("Sunday")
You can set which item should shown while it displaying in the form for first time.
ComboBox1.SelectedItem = ComboBox1.Items(3)
When you run the above code it will show the forth item in the combobox. The item index is starting from 0. If you want to retrieve the displayed item to a string variable , you can code like this
Dim var As String var = ComboBox1.Text
You can remove items from a combobox in two ways. You can remove item at a the specified index or giving a specified item by name.
ComboBox1.Items.RemoveAt(1)
The above code will remove the second item from the combobox.
ComboBox1.Items.Remove("Friday")
The above code will remove the item "Friday" from the combobox. The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop down. The DropDownStyle property also specifies whether the text portion can be edited.
ComboBox1.DropDownStyle = ComboBoxStyle.DropDown
The following VB.Net source code add seven days in a week to a combo box while load event of a Windows Form and display the fourth item in the combobox. Download Source Code Print Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ComboBox1.Items.Add("Sunday") ComboBox1.Items.Add("Monday") ComboBox1.Items.Add("Tuesday") ComboBox1.Items.Add("wednesday") ComboBox1.Items.Add("Thursday") ComboBox1.Items.Add("Friday") ComboBox1.Items.Add("Saturday") ComboBox1.SelectedItem = ComboBox1.Items(3) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As String var = ComboBox1.Text MsgBox(var) End Sub End Class
ListBox Control
VB.Net provides several mechanisms for gathering input in a program. A Windows Forms ListBox control displays a list of choices which the user can select from.
You can use the Add or Insert method to add items to a list box. The Add method adds new items at the end of an unsorted list box. The Insert method allows you to specify where to insert the item you are adding.
ListBox1.Items.Add("Sunday")
The SelectionMode property determines how many items in the list can be selected at a time. A ListBox control can provide single or multiple selections using the SelectionMode property . If you want to retrieve a single selected item to a variable , you can code like this
Dim var As String var = ListBox1.SelectedItem
If you change the selection mode property to multiple select , then you will retrieve a collection of items from ListBox1.SelectedItems property.
ListBox1.SelectionMode = SelectionMode.MultiSimple
The following VB.Net program initially fill seven days in a week while in the form load event and set the selection mode property to MultiSimple. At the Button click event it will display the selected items. Download Source Code Print Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ListBox1.Items.Add("Sunday") ListBox1.Items.Add("Monday") ListBox1.Items.Add("Tuesday") ListBox1.Items.Add("Wednesday") ListBox1.Items.Add("Thursday") ListBox1.Items.Add("Friday") ListBox1.Items.Add("Saturday") ListBox1.SelectionMode = SelectionMode.MultiSimple End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim obj As Object For Each obj In ListBox1.SelectedItems MsgBox(obj.ToString) Next End Sub End Class
To add objects to the list at run time, assign an array of object references with the AddRange method. The list then displays the default string value for each object.
Dim days As String() = {"Sunday", "Monday", "Tuesday"}
checkedListBox1.Items.AddRange(days)
You can add individual items to the list with the Add method. The CheckedListBox object supports three states through the CheckState enumeration: Checked, Indeterminate, and Unchecked.
CheckedListBox1.Items.Add("Sunday", CheckState.Checked) CheckedListBox1.Items.Add("Monday", CheckState.Unchecked) CheckedListBox1.Items.Add("Tuesday", CheckState.Indeterminate)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load CheckedListBox1.Items.Add("Sunday", CheckState.Checked) CheckedListBox1.Items.Add("Monday", CheckState.Unchecked) CheckedListBox1.Items.Add("Tuesday", CheckState.Indeterminate) CheckedListBox1.Items.Add("Wednesday", CheckState.Checked) CheckedListBox1.Items.Add("Thursday", CheckState.Unchecked) CheckedListBox1.Items.Add("Friday", CheckState.Indeterminate) CheckedListBox1.Items.Add("Saturday", CheckState.Indeterminate) End Sub End Class
RadioButton Control
A radio button or option button is a type of graphical user interface element that allows the user to choose only one of a predefined set of options. When a user clicks on a radio button, it becomes checked, and all other radio buttons with same group become unchecked
The radio button and the check box are used for different functions. Use a radio button when you want the user to choose only one option. When you want the user to choose all appropriate options, use a check box. Like check boxes, radio buttons support a Checked property that indicates whether the radio button is selected. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load RadioButton1.Checked = True End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If RadioButton1.Checked = True Then MsgBox("You are selected Red !! ") Exit Sub ElseIf RadioButton2.Checked = True Then MsgBox("You are selected Blue !! ") Exit Sub Else MsgBox("You are selected Green !! ") Exit Sub End If End Sub End Class
CheckBox Control
CheckBoxes allow the user to make multiple selections from a number of options. You can click a check box to select it and click it again to deselect it.
CheckBoxes comes with a caption, which you can set in the Text property.
CheckBox1.Text = "Net-informations.com"
You can use the CheckBox control ThreeState property to direct the control to return the Checked, Unchecked, and Indeterminate values. You need to set the check boxs ThreeState property to True to indicate that you want it to support three states.
CheckBox1.ThreeState = True
To apply the same property settings to multiple CheckBox controls, use the Style property. The following VB.Net program shows how to find a checkbox is selected or not. Download Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim msg As String = ""
If CheckBox1.Checked = True Then msg = "net-informations.com" End If If CheckBox2.Checked = True Then msg = msg & " vb.net-informations.com" End If If CheckBox3.Checked = True Then msg = msg & " csharp.net-informations.com" End If If msg.Length > 0 Then MsgBox(msg & " selected ") Else MsgBox("No checkbox selected") End If CheckBox1.ThreeState = True End Sub End Class
PictureBox Control
The Windows Forms PictureBox control is used to display images in bitmap, GIF,icon, or JPEG formats.
You can set the Image property to the Image you want to display, either at design time or at run time. You can programmatically change the image displayed in a picture box, which is particularly useful when you use a single form to display different pieces of information.
PictureBox1.Image = Image.FromFile("C:\testImage.jpg")
The SizeMode property, which is set to values in the PictureBoxSizeMode enumeration, controls the clipping and positioning of the image in the display area.
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
You can change the size of the display area at run time with the ClientSize property.
pictureBox1.ClientSize = New Size(xSize, ySize)
The following VB.Net program shows how to load a picture from a file and display it in streach mode. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox1.Image = Image.FromFile("d:\testImage.jpg") PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage End Sub End Class
ScrollBars Control
The horizontal and vertical scrollbars which the user can use to move content into view.
Most of the controls that use scrollbars come with them built in, such as multiline text boxes, combo boxes etc. You can set the Value property yourself in code, which moves the scroll box to match. The controls Value property gets and sets its current numeric value. The Minimum and Maximum properties determine the range of values that the control can display. The following VB.Net program shows a TextBox control with scrollbars. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Multiline = True TextBox1.ScrollBars = ScrollBars.Both End Sub End Class
ListView Control
List views displays a collection of items that can be displayed using one of five different views, such as LargeIcon, Details , SmallIcon, List and Tile.
ListView provides a large number of properties that provide flexibility in appearance and behavior. The View property allows you to change the way in which items are displayed. and the SelectionMode property determines how many items in the list can be selected at a time. The following Vb.Net program first set its view property as Details and GridLines property as true and FullRowSelect as true.
ListView1.View = View.Details ListView1.GridLines = True ListView1.FullRowSelect = True
After that it fills column header and then the column values.
ListView1.Columns.Add("ProductName", 100)
Finally in the button click event, it will display the selected row values in a message box. Download Source Code Print Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ''Set view property ListView1.View = View.Details ListView1.GridLines = True ListView1.FullRowSelect = True 'Add column header ListView1.Columns.Add("ProductName", 100) ListView1.Columns.Add("Price", 70) ListView1.Columns.Add("Quantity", 70) 'Add items in the listview Dim arr(3) As String Dim itm As ListViewItem 'Add first item arr(0) = "product_1" arr(1) = "100" arr(2) = "10" itm = New ListViewItem(arr) ListView1.Items.Add(itm) 'Add second item arr(0) = "product_2" arr(1) = "200" arr(2) = "20" itm = New ListViewItem(arr) ListView1.Items.Add(itm) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim productName As String Dim price As String Dim quantity As String productName = ListView1.SelectedItems.Item(0).SubItems(0).Text price = ListView1.SelectedItems.Item(0).SubItems(1).Text quantity = ListView1.SelectedItems.Item(0).SubItems(2).Text MsgBox(productName & " , " & price & " , " & quantity) End Sub End Class
MDI Form
A Multiple Document Interface (MDI) programs can display multiple child windows inside them.
This is in contrast to single document interface (SDI) applications, which can manipulate only one document at a time. Visual Studio Environment is an example of Multiple Document Interface (MDI) and notepad is an example of an SDI application, opening a document closes any previously opened document. Any windows can become an MDI parent, if you set the IsMdiContainer property to True.
IsMdiContainer = True
The following vb.net program shows a MDI form with two child forms. Create a new VB.Net project, then you will get a default form Form1 . Then add two mnore forms in the project (Form2 , Form 3) . Create a Menu on your form and call these two forms on menu click event. Click the following link to see how to create a Menu on your form How to Menu Control VB.Net. Download Source Code
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load IsMdiContainer = True End Sub Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MenuItem1ToolStripMenuItem.Click Dim frm2 As New Form2 frm2.Show() frm2.MdiParent = Me End Sub Private Sub MenuItem2ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2ToolStripMenuItem.Click Dim frm3 As New Form3 frm3.Show() frm3.MdiParent = Me End Sub End Class
index : The position of the item in an ArrayList Item : The Item to be add the ArrayList ItemList.Insert(3, "item6") How to remove an item from arrayList ? Syntax : ArrayList.Remove(item) Item : The Item to be add the ArrayList ItemList.Remove("item2") How to remove an item in a specified position from an ArrayList ? Syntax : ArrayList.RemoveAt(index) index : the position of an item to remove from an ArrayList ItemList.RemoveAt(2) How to sort ArrayList ? Syntax : ArrayListSort() The following VB.NET source code shows some function in ArrayList Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim ItemList As New ArrayList() ItemList.Add("Item4") ItemList.Add("Item5") ItemList.Add("Item2") ItemList.Add("Item1") ItemList.Add("Item3") MsgBox("Shows Added Items") For i = 0 To ItemList.Count - 1 MsgBox(ItemList.Item(i)) Next 'insert an item ItemList.Insert(3, "Item6") 'sort itemms in an arraylist ItemList.Sort() 'remove an item
ItemList.Remove("Item1") 'remove item from a specified index ItemList.RemoveAt(3) MsgBox("Shows final Items the ArrayList") For i = 0 To ItemList.Count - 1 MsgBox(ItemList.Item(i)) Next End Sub End Class
When you execute this program , at first add five items in the arraylist and displays. Then again one more item inserted in the third position , and then sort all items. Next it remove the item1 and also remove the item in the third position . Finally it shows the existing items.
The following source code shows all important operations in a HashTable Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim weeks As New Hashtable Dim day As DictionaryEntry weeks.Add("1", "Sun") weeks.Add("2", "Mon") weeks.Add("3", "Tue") weeks.Add("4", "Wed") weeks.Add("5", "Thu") weeks.Add("6", "Fri") weeks.Add("7", "Sat") 'Display a single Item MsgBox(weeks.Item("5")) 'Search an Item If weeks.ContainsValue("Tue") Then MsgBox("Find") Else MsgBox("Not find") End If 'remove an Item weeks.Remove("3") 'Display all key value pairs For Each day In weeks MsgBox(day.Key " -- " day.Value) Next End Sub End Class
When you execute this program it add seven weekdays in the hashtable and display the item 5. Then it check the item "Tue" is existing or not . Next it remove the third item from HashTable. Finaly it displays all item exist in the HashTable.
Object : The item to be inserted. Pop : Pop return the item last Item to insert in stack Syntax : Stack.Pop() Return : The last object in the Stack Contains : Check the object contains in the stack Syntax : Stack.Contains(Object) Object : The specified Object to be seach The following VB.NET Source code shows some of commonly used functions : Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stackTable As New Stack stackTable.Push("Sun") stackTable.Push("Mon") stackTable.Push("Tue") stackTable.Push("Wed") stackTable.Push("Thu") stackTable.Push("Fri") stackTable.Push("Sat") If stackTable.Contains("Wed") Then MsgBox(stackTable.Pop()) Else MsgBox("not exist") End If End Sub End Class
When you execute this program add seven items in the stack . Then its checks the item "Wed" exist in the Stack. If the item exist in the Stack , it Pop the last item from Stack , else it shows the msg "Not Exist
The commonly using functions are follows : Enqueue : Add an Item in Queue Syntax : Stack.Enqueue(Object) Object : The item to add in Queue Dequeue : Remove the oldest item from Queue (we dont get the item later) Syntax : Stack.Dequeue() Returns : Remove the oldest item and return. Peek : Get the reference of the oldest item (it is not removed permenantly) Syntax : Stack.Peek() returns : Get the reference of the oldest item in the Queue The following VB.NET Source code shows some of commonly used functions : Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click Dim queueList As New Queue queueList.Enqueue("Sun") queueList.Enqueue("Mon") queueList.Enqueue("Tue") queueList.Enqueue("Wed") queueList.Enqueue("Thu") queueList.Enqueue("fri") queueList.Enqueue("Sat") MsgBox(queueList.Dequeue()) MsgBox(queueList.Peek()) If queueList.Contains("Sun") Then MsgBox("Contains Sun ") Else MsgBox("Not Contains Sun ") End If End Sub End Class
When you execute the program it add seven items in the Queue. Then it Dequeue (remove) the oldest item from queue. Next it Peek() the oldest item from Queue (shows only , not remove ).
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim week(6) As String week(0) = "Sunday" week(1) = "Monday" week(2) = "Tuesday" week(3) = "Wednesday" week(4) = "Thursday" week(5) = "Friday" week(6) = "Saturday" For i = 0 To week.Length - 1 MsgBox(week(i)) Next End Sub End Class
When you execute this program you will get the Days in a Week .
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer Dim scores() As Integer ReDim scores(1) scores(0) = 100 scores(1) = 200 For i = 0 To scores.Length - 1 MsgBox(scores(i)) Next ReDim Preserve scores(2) scores(2) = 300
When you execute this source code , the first loop shows first two values stored in the Array. Next loop shows the whole value stored in the Array.
Imports System.Collections.Specialized Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim markStatus As New NameValueCollection Dim key As String Dim values() As String markStatus.Add("Very High", "80") markStatus.Add("High", "60") markStatus.Add("medium", "50") markStatus.Add("Pass", "40") For Each key In markStatus.Keys values = markStatus.GetValues(key) For Each value As String In values MsgBox(key & " - " & value)
When you execute this source code , you will get each Key/Value sets.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "This is a Test" MsgBox(str.Length()) End Sub End Class
When you execute this source code you will get 17 in the messagebox
Returns: String - The result string. Exceptions: System.ArgumentOutOfRangeException: startIndex is negative or greater than the length of this instance System.ArgumentNullException : If the argument is null. For ex: "This is Test".Insert(8,"Insert ") returns "This is Insert Test" Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "This is VB.NET Test" Dim insStr As String = "Insert " Dim strRes As String = str.Insert(15, insStr) MsgBox(strRes) End Sub End Class
When you execute this program you will get the message box showing "This is VB.NET Insert Test"
If it does not occur as a substring, -1 is returned. Exceptions: System.ArgumentNullException: If the Argument is null. For ex: "This is a test".IndexOf("Test") returns 10 "This is a test".IndexOf("vb") returns -1 Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" MsgBox(str.IndexOf("BOOKS")) End Sub End Class
When you execute this program you will get the number 14 in the message box. That means the substring "BOOKS" occurred and start in the position 14.
System.ArgumentNullException : The format String is null. System.FormatException : The format item in format is invalid. The number indicating an argument to format is less than zero, or greater than or equal to the number of specified objects to format. For ex : Currency : String.Format("{0:c}", 10) will return $10.00 The currency symbol ($) displayed depends on the global locale settings. Date : String.Format("Today's date is {0:D}", DateTime.Now) You will get Today's date like : 01 January 2005 Time : String.Format("The current time is {0:T}", DateTime.Now) You will get Current Time Like : 10:10:12 Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim dNum As Double dNum = 32.123456789 MsgBox("Formated String " & String.Format("{0:n4}", dNum)) End Sub End Class
When you run this source code yo will get "Formated String 32.1234"
String str1 : The String argument String str2 : The String argument Returns: Boolean : Yes/No It return the values of the two String Objects are same For ex : Str1 = "Equals()" Str2 = "Equals()" String.Equals(Str1,Str2) returns True String.Equals(Str1.ToLower,Str2) returns False Because the String Objects values are different Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String = "Equals" Dim str2 As String = "Equals" If String.Equals(str1, str2) Then MsgBox("Strings are Equal() ") Else MsgBox("Strings are not Equal() ") End If End Sub End Class
When you run this program you will get message "Strings are Equal() "
Parameters: Integer sourceIndex : The starting position of the source String Char destination() : The character Array Integer destinationIndex : Array element in the destination Integer count : The number of characters to destination Exceptions: System.ArgumentNullException : If the destination is null System.ArgumentOutOfRangeException : Source Index, DestinationIndes or Count is a -ve value Count is greater than the length of the substring from startIndex to the end of this instance count is greater than the length of the subarray from destinationIndex to the end of destination Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String = "CopyTo() sample" Dim chrs(5) As Char str1.CopyTo(0, chrs, 0, 6) MsgBox(chrs(0) + chrs(1) + chrs(2) + chrs(3) + chrs(4) + chrs(5)) End Sub End Class
When you run this Source code you will get CopyTo in MessageBox
String : Returns a new String as the same content of argument String Exceptions: System.ArgumentNullException : If the argument is null. Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "VB.NET Copy() test" str2 = String.Copy(str1) MsgBox(str2) End Sub End Class
When you run this source code you will get same content of str1 in str2
System.ArgumentNullException : If the argument is null Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" If str.Contains("TOP") = True Then MsgBox("The string Contains() 'TOP' ") Else MsgBox("The String does not Contains() 'TOP'") End If End Sub End Class
When you run the program you will get the MessageBox with message "The string Contains() 'TOP' "
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "vb.net" str2 = "VB.NET" Dim result As Integer result = String.Compare(str1, str2) MsgBox(result) result = String.Compare(str1, str2, True) MsgBox(result) End Sub End Class
When you run this program first u get -1 in message box and then 0
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String = "Returned Character Chars()" Dim singleChar As Char singleChar = str.Chars(3) MsgBox(singleChar) End Sub End Class
When you run this source code you will return a messagebox show 'u'
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String Dim retString As String str = "This is substring test" retString = str.Substring(8, 9) MsgBox(retString) End Sub End Class
When you execute this program , its will display "subtring" in the messagebox.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str As String Dim strArr() As String Dim count As Integer str = "vb.net split test" strArr = str.Split(" ") For count = 0 To strArr.Length - 1 MsgBox(strArr(count)) Next End Sub End Class
When you execute this programme , you will get "vb.net" "split" "test" in separate messagebox.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim str As String str = "VB.NET TOP 10 BOOKS" If str.EndsWith("BOOKS") = True Then MsgBox("The String EndsWith 'BOOKS' ") Else MsgBox("The String does not EndsWith 'BOOKS'") End If End Sub End Class
When you execute the program you will get a message box like "The String EndsWith 'BOOKS'
Concat in VB.NET String Class using for concat two specified String Object System.String.Concat(ByVal str1 As String, ByVal str2 As String) As String String Concat method returns a new String Parameters: String str1 : Parameter String String str2 : Parameter String Returns: String : A new String retrun with str1 Concat with str2 Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim str1 As String Dim str2 As String str1 = "Concat() " str2 = "Test" MsgBox(String.Concat(str1, str2)) End Sub End Class
When you run this source code you will get "Concat() Test " in message box.
VB.NET : Directory.CreateDirectory("c:\testdir") How to check a directory exist or not ? Before we creating a directory , we usually check that directory exist or not. For that we are using the Exists method in the Directory class. Syntax : Directory.Exists(DirPath) as Boolean DirPath : The name of the directory Boolean : Returns true or false , if directory exist it Returns true , else it Returns false VB.NET : Directory.Exists("c:\testdir") How to move a Directory ? If we want to move a directory and its contents from one location to another , we can use the Move method in the Directory class. Syntax : Move(sourceDirName,destDirName) sourceDirName : The source directory we want to move. destDirName : The destinations directory name. VB.NET : Directory.Move("c:\testdir1\testdir2", "c:\testdir") How to delete a Directory ? When we want to delete a directory we can use the Delete method in the Directory class Syntax : Delete(DirPath) DirPath : The Directory we want to delete. VB.NET : Directory.Delete("c:\testdir1") The following VB.NET source code shows these operations : Download Source Code Print Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object,_ ByVal e As System.EventArgs) Handles Button1.Click
If Directory.Exists("c:\testDir1") Then 'shows message if testdir1 exist MsgBox("Directory 'testDir' Exist ") Else 'create the directory testDir1 Directory.CreateDirectory("c:\testDir1") MsgBox("testDir1 created ! ") 'create the directory testDir2 Directory.CreateDirectory("c:\testDir1\testDir2") MsgBox("testDir2 created ! ") 'move the directory testDir2 as testDir in c: Directory.Move("c:\testDir1\testDir2", "c:\testDir") MsgBox("testDir2 moved ") 'delete the directory testDir1 Directory.Delete("c:\testDir1") MsgBox("testDir1 deleted ") End If End Sub End Class
When you executing this program you can see , first it create directory testDir1 and then testDir2 is creating inside testDir1 , Next the program move the testDir2 to testDir . Finally it delete the directory testDir1. After the execution you can see testDir in c:\
Syntax : File.Exists(FilePath) as Boolean FilePath : The name of the File Boolean : Returns true or false , if File exist it Returns true else Returns false VB.NET : File.Exists("c:\testFile.txt") The following VB.NET source code shows these operations :
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If File.Exists("c:\testFile.txt") Then 'shows message if testFile exist MsgBox("File 'testFile' Exist ") Else 'create the file testFile.txt File.Create("c:\testFile.txt") MsgBox("File 'testFile' created ") End If End Sub End Class
When you execute this source code , it first check the File exist or not , If exist it shows message file exist , else it create a new File Object . How to Copy a File ? If we want the Copy of the File Object we can use the Copy method in File class. Syntax : Copy(sourceFileName, destFileName) sourceFileName : The source file we want to move. destFileName : The destinations file name. VB.NET : File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt") How to delete a File Object ? When we want to delete a File Object we can use the Delete methods in the File class Syntax : Delete(FilePath) DirPath : The File Object you want to delete.
VB.NET : File.Delete("c:\testDir\testFile.txt") The following VB.NET source code shows these operations : Download Source Code Print Source Code
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If Not File.Exists("c:\testFile.txt") Then MsgBox("FIle not exist ") Else File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt") MsgBox("File Copied ") File.Delete("c:\testFile.txt") MsgBox("file deleted ") End If End Sub End Class
When you execute this program first it check whether the file exist or not , if it is not exist it shows message file does not exist, if it exist it copied the file to testDir director and it delete the file from the c:\.
Imports System.IO Imports System.Text Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim wFile As System.IO.FileStream Dim byteData() As Byte byteData = Encoding.ASCII.GetBytes("FileStream Test1") wFile = New FileStream("streamtest.txt", FileMode.Append) wFile.Write(byteData, 0, byteData.Length) wFile.Close() Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class
When we execute the program , it create a new File and write the content to it .
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim line As String Dim readFile As System.IO.TextReader = New _ StreamReader("C:\TextReader.txt") While True line = readFile.ReadLine() If line Is Nothing Then Exit While Else MsgBox(line) End If End While readFile.Close() readFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try
When you execute this program the TextReader read the file line by line.
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim line As String Dim readFile As System.IO.TextReader = New _ StreamReader("C:\Test1.txt") line = readFile.ReadToEnd() MsgBox(line) readFile.Close() readFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class
When you execute this program , TextReader read the entire file in one stretch.
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Try Dim writeFile As System.IO.TextWriter = New _
StreamWriter("c:\textwriter.txt") writeFile.WriteLine("vb.net-informations.com") writeFile.Flush() writeFile.Close() writeFile = Nothing Catch ex As IOException MsgBox(ex.ToString) End Try End Sub End Class
When you execute this source code , you will get a file TextWriter.txt and inside it written vb.net-informations.com .
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim readStream As FileStream Dim msg As String Try readStream = New FileStream("c:\testBinary.dat", FileMode.Open) Dim readBinary As New BinaryReader(readStream) msg = readBinary.ReadString() MsgBox(msg) readStream.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim writeStream As FileStream Try writeStream = New FileStream("c:\testBinary.dat", FileMode.Create) Dim writeBinay As New BinaryWriter(writeStream) writeBinay.Write("This is a test for BinaryWriter !") writeBinay.Close() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
In some situations we have to find how many tables inside the Dataset Object contains . The following VB.NET source code shows how to find the tables inside the Dataset. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim tables As DataTable Dim i As Integer Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() For Each tables In ds.Tables MsgBox(tables.TableName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here"
members, corresponding to the number of rows. The following VB.NET source code shows how to find the number of rows in a table that resides in the Dataset. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() MsgBox("Number of row(s) " & ds.Tables(0).Rows.Count)
Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here"
In some situations we have to find the column headers in a DataTable. There is a ColumnsCollection object in the Datatable hold the column Definitions. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim column As DataColumn Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() dt = ds.Tables(0) For Each column In dt.Columns MsgBox(column.ColumnName) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here"
to the number of rows. We can fill the data in Dataset without calling SQL statements. For that we manually create a DataTable and add data in it. Download Source Code Print Source Code
Imports System.Data.OleDb Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim dt As DataTable Dim dr As DataRow Dim idCoulumn As DataColumn Dim nameCoulumn As DataColumn Dim i As Integer dt = New DataTable() idCoulumn = New DataColumn("ID", Type.GetType("System.Int32")) nameCoulumn = New DataColumn("Name", Type.GetType("System.String")) dt.Columns.Add(idCoulumn) dt.Columns.Add(nameCoulumn) dr = dt.NewRow() dr("ID") = 1 dr("Name") = "Name1" dt.Rows.Add(dr) dr = dt.NewRow() dr("ID") = 2 dr("Name") = "Name2" dt.Rows.Add(dr) ds.Tables.Add(dt) For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " ds.Tables(0).Rows(i).Item(1)) Next i End Sub End Class -" &
We can populate Dataset with more than one table at a time using SqlDataAdapter Object . The following VB.NET source code shows how to a single SqlDataAdapter fill Dataset with multiple tables. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "First Table") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Second Table") adapter.Dispose() command.Dispose() connection.Close() 'retrieve first table data For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(0) & " ds.Tables(0).Rows(i).Item(1)) Next 'retrieve second table data For i = 0 To ds.Tables(1).Rows.Count - 1 MsgBox(ds.Tables(1).Rows(i).Item(0) & " ds.Tables(1).Rows(i).Item(1)) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub
--
" &
--
" &
End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here"
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim firstSql As String Dim secondSql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table1") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table2") adapter.Dispose() command.Dispose() connection.Close() 'creating data relations Dim relation As DataRelation Dim table1Column As DataColumn Dim table2Column As DataColumn 'retrieve column table1Column = ds.Tables("Table1").Columns(0)
table2Column = ds.Tables("table2").Columns(0) 'relating tables relation = New DataRelation("relation", table1Column, table2Column) 'assign relation to dataset ds.Relations.Add(relation) MsgBox("Data relation completed") Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here"
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dt As DataTable Dim firstSql As String Dim secondSql As String Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here"
connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(firstSql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Table(0)") adapter.SelectCommand.CommandText = secondSql adapter.Fill(ds, "Table(1)") adapter.Dispose() command.Dispose() connection.Close() ds.Tables(0).Merge(ds.Tables(1)) dt = ds.Tables(0) For i = 0 To dt.Rows.Count - 1 MsgBox(dt.Rows(i).Item(0) & " -Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class " & dt.Rows(i).Item(1))
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" firstSql = "Your First SQL Statement Here" secondSql = "Your Second SQL Statement Here"
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter
Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Try connection.Open() adapter = New SqlDataAdapter("Your SQL Statement Here", connection) adapter.Fill(ds) connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1)) Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim i As Integer connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Try connection.Open() adapter.SelectCommand = New SqlCommand("Your SQL Statement Here", connection) adapter.Fill(ds) connection.Close() For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(1)) Next Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "insert into product (Product_id,Product_name,Product_price) values(7,'Product7',700)" Try connection.Open() adapter.InsertCommand = New SqlCommand(sql, connection) adapter.InsertCommand.ExecuteNonQuery() MsgBox("Row inserted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
SqlDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications, that are run on a DataSet object. The following code samples that demonstrate how to use the SqlDataAdapter object to update a SQL Server database using UpdateCommand properties in SqlDataAdapter. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "update product set product_price = 1001 where Product_name ='Product7'" Try connection.Open() adapter.UpdateCommand = connection.CreateCommand adapter.UpdateCommand.CommandText = sql adapter.UpdateCommand.ExecuteNonQuery() MsgBox("Row updated !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As New SqlDataAdapter Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) sql = "delete product where Product_name ='Product7'" Try connection.Open() adapter.DeleteCommand = connection.CreateCommand adapter.DeleteCommand.CommandText = sql adapter.DeleteCommand.ExecuteNonQuery() MsgBox("Row(s) deleted !! ") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
System.EventArgs) Handles Button1.Click connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" connection = New SqlConnection(connetionString) Sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(Sql, connection) adapter.Fill(ds) connection.Close() DataGridView1.Data Source= ds.Tables(0) Catch ex As Exception MsgBox(ex.ToString) End Try End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try cmdBuilder = New SqlCommandBuilder(adapter) changes = ds.GetChanges() If changes IsNot Nothing Then adapter.Update(changes) End If MsgBox("Changes Done") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Create DataView") adapter.Dispose() command.Dispose() connection.Close() dv = ds.Tables(0).DefaultView DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Sort DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price > 100", "Product_Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Add New") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) Dim newRow As DataRowView = dv.AddNew() newRow("Product_ID") = 7 newRow("Product_Name") = "Product 7" newRow("Product_Price") = 111 newRow.EndEdit() dv.Sort = "product_id" DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Dim index As Integer = DataView.Find("Product5") Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Find Row DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) dv.Sort = "Product_Name" Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_id").ToString() & " ("Product_Name").ToString()) End If Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
We can update the data in a DataView . The following source code shows how to update data in a DataView . Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Update") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_Name", DataViewRowState.CurrentRows) Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Product not found") Else dv(index)("Product_Name") = "Product11" MsgBox("Product Updated !") End If DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
content in a DataTable. Also we can delete the data from the DataView . The following source code shows how to delete the data from DataView. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Delete Row") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "", "Product_ID", DataViewRowState.CurrentRows) dv.Table.Rows(3).Delete() DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim dv As DataView Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Select * from product" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Copy to DataTable") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price <= 200", "Product_ID", DataViewRowState.CurrentRows) Dim dTable As DataTable dTable = dv.ToTable DataGridView1.DataSource = dTable Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Titles" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Titles_table") connection.Close() Dim dv As DataView dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv End Sub
End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) DataGridView1.Rows(1).Visible = False End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim btn As New DataGridViewButtonColumn() DataGridView1.Columns.Add(btn) btn.HeaderText = "Click Data" btn.Text = "Click Here" btn.Name = "btn" btn.UseColumnTextForButtonValue = True End Sub Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick If e.ColumnIndex = 3 Then MsgBox(("Row : " + e.RowIndex.ToString & " Col : ") + e.ColumnIndex.ToString) End If End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row) Dim chk As New DataGridViewCheckBoxColumn() DataGridView1.Columns.Add(chk) chk.HeaderText = "Check Data" chk.Name = "chk" DataGridView1.Rows(2).Cells(3).Value = True End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim cmb As New DataGridViewComboBoxColumn() cmb.HeaderText = "Select Data" cmb.Name = "cmb" cmb.MaxDropDownItems = 4 cmb.Items.Add("True") cmb.Items.Add("False") DataGridView1.Columns.Add(cmb) End Sub End Class
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim img As New DataGridViewImageColumn() Dim inImg As Image = Image.FromFile("Image Path") img.Image = inImg DataGridView1.Columns.Add(img) img.HeaderText = "Image" img.Name = "img" End Sub End Class
The following vb.net program shows how to add a hyperlink in a column of DataGridView control. Download Source Code Print Source Code
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).Name = "Product ID" DataGridView1.Columns(1).Name = "Product Name" DataGridView1.Columns(2).Name = "Product_Price" Dim row As String() = New String() {"1", "Product 1", "1000"} DataGridView1.Rows.Add(row) row = New String() {"2", "Product 2", "2000"} DataGridView1.Rows.Add(row) row = New String() {"3", "Product 3", "3000"} DataGridView1.Rows.Add(row) row = New String() {"4", "Product 4", "4000"} DataGridView1.Rows.Add(row) Dim lnk As New DataGridViewLinkColumn() DataGridView1.Columns.Add(lnk) lnk.HeaderText = "Link Data" lnk.Name = "http://vb.net-informations.com" lnk.Text = "http://vb.net-informations.com" lnk.UseColumnTextForLinkValue = True End Sub End Class
The DataGridView class allows customization of cells, rows, columns, and borders through the use of its properties . If a DataGridView has lot of rows then we can implement paging functionalities to the DataGridView control. While we implement paging we should know the boundaries of the pages to enable the paging in the DatagridView. The following vb.net program provides a way to programmatically implement paging in a Windows Datagrid View control. Here the DataGridView rows fixed as five rows and other two buttons are there for implementing paging functionalities. Download Source Code
Imports System.Data.SqlClient Public Class Form1 Dim pagingAdapter As SqlDataAdapter Dim pagingDS As DataSet Dim scrollVal As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM authors" Dim connection As New SqlConnection(connectionString) pagingAdapter = New SqlDataAdapter(sql, connection) pagingDS = New DataSet() connection.Open() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") connection.Close()
DataGridView1.DataSource = pagingDS DataGridView1.DataMember = "authors_table" End Sub Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click scrollVal = scrollVal - 5 If scrollVal <= 0 Then scrollVal = 0 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click scrollVal = scrollVal + 5 If scrollVal > 23 Then scrollVal = 18 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub End Class
identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.
.Net Metadata
Metadata in .Net is binary information which describes the characteristics of a resource . This information include Description of the Assembly , Data Types and members with their declarations and implementations, references to other types and members , Security permissions etc. A module's metadata contains everything that needed to interact with another module. During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference.
.Net Assembly
Microsoft .Net Assembly is a logical unit of code, it contains code that the Common Language Runtime (CLR) executes. Assembly is really a collection of types and resource information that are built to work together and form a logical unit of functionality. During the compile time Metadata is created, with Microsoft Intermediate Language (MSIL), and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. Manifest contains information about itself. This information is called Assembly Manifest, it contains information about the members, types, references and all the other data that the runtime needs for execution. Every Assembly you create contains one or more program files and a Manifest. There are two types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can have only one entry point (that is, DllMain, WinMain, or Main). We can create two types of Assembly, private Assembly and shared Assembly . A private Assembly is used only by a single application, and usually it is stored in that application's install directory. A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC).
To create a key pair At the command prompt, type the following command: sn -k fileName
In this command, file name is the name of the output file containing the key pair.
.Net Namespaces
Namespaces are the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification. The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes.
These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL ) by using the full Namespaces of the class .In .Net languages every program is created with a default Namespaces . Programmers can also create their own Namespaces in .Net languages.
.Net Namespaces
Namespaces are the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification. The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes.
These Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL ) by using the full Namespaces of the class .In .Net languages every program is created with a default Namespaces . Programmers can also create their own Namespaces in .Net languages.
the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating System. When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Metadata. The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable executable (PE) file . Microsoft Intermediate Language (MSIL) includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations
allowed to run, and what resources it can use when it is running. Code Access Security policy uses evidence to help grant the right permissions to the right assembly. An administrator can configure Code Access Security policy to restrict the resource types that code can access and the other privileged operations it can perform. Code Access Security allows code to be trusted to varying degrees depending on where the code originates and on other aspects of the code's identity. Code Access Security can also help minimize the damage that can result from security vulnerabilities in your code.
Garbage Collection
The .Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap. The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.
Imports System.Net Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim inStream As StreamReader Dim webRequest As WebRequest Dim webresponse As WebResponse webRequest = webRequest.Create(TextBox1.Text) webresponse = webRequest.GetResponse() inStream = New StreamReader(webresponse.GetResponseStream()) TextBox2.Text = inStream.ReadToEnd() End Sub End Class
Imports System.Net.Mail Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click Try Dim SmtpServer As New SmtpClient() Dim mail As New MailMessage() SmtpServer.Credentials = New _ Net.NetworkCredential("username@gmail.com", "password") SmtpServer.Port = 587 SmtpServer.Host = "smtp.gmail.com" mail = New MailMessage() mail.From = New MailAddress("YOURusername@gmail.com") mail.To.Add("TOADDRESS") mail.Subject = "Test Mail" mail.Body = "This is for testing SMTP mail from GMAIL" SmtpServer.Send(mail) MsgBox("mail send") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
You have to provide the informations like your gmail username and password , and the to address also.
If the contition is TRUE then the control goes to between IF and Else block , that is the program will execute the code between IF and ELSE statements. If the contition is FLASE then the control goes to between ELSE and END IF block , that is the program will execute the code between ELSE and END IF statements. If you want o check more than one condition at the same time , you can use ElseIf .
If [your condition here] Your code here ElseIf [your condition here] Your code here ElseIf [your condition here] Your code here
Else End If
Just take a real-time example - When we want to analyze a mark lists we have to apply some conditions for grading students depends on the marks. Following are the garding rule of the mark list: 1) If the marks is greater than 80 then the student get higher first class 2) If the marks less than 80 and greater than 60 then the student get first class 3) If the marks less than 60 and greater than 40 then the student get second class 4) The last condition is , if the marks less than 40 then the student fail. Now here implementing these conditions in a VB.NET program.
1. 2. 3. 4. 5. 6. 7. 8. 9. If totalMarks >= 80 Then MsgBox("Got Higher First Class ") ElseIf totalMarks >= 60 Then MsgBox("Got First Class ") ElseIf totalMarks >= 40 Then MsgBox("Just pass only") Else MsgBox("Failed") End If
Line 1 : Checking the total marks greaterthan or equal to 80 Line 2 : If total marks greater than 80 show message - "Got Higher First Class " Line 3 : Checking the total marks greaterthan or equal to 60 Line 4 : If total marks greater than 60 show message - "Got First Class " Line 5 : Checking the total marks greaterthan or equal to 40 Line 6 : If total marks greater than 40 show message - "Just pass only" Line 7 : If those three conditions failed program go to the next coding block Line 8 : If all fail shows message "Failed" Line 9 : Ending the condition block VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim totalMarks As Integer totalMarks = 59 If totalMarks >= 80 Then MsgBox("Gor Higher First Class ") ElseIf totalMarks >= 60 Then MsgBox("Gor First Class ") ElseIf totalMarks >= 40 Then MsgBox("Just pass only") Else MsgBox("Failed") End If End Sub End Class
In this example the total marks is 59 , when you execute this program you will get in messagebox "Just Pass Only" If you want to check a condition within condition you can use nested if statements
If [your condition here] If [your condition here] Your code here Else Your code Here End If Else Your code Here End If
Also you can write IF ELSE Statements in a single line If [your condition here] [Code] Else [code] Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim totalMarks As Integer totalMarks = 39 If totalMarks >= 50 Then MsgBox("passed ") Else MsgBox("Failed ") End Sub End Class
When you execute this program you will get in messagebox "Failed "
var : The counter for the loop to repeat the steps. starValue : The starting value assign to counter variable . endValue : When the counter variable reach end value the Loop will stop . loopBody : The source code between loop body Lets take a simple real time example , If you want to show a messagebox 5 times and each time you want to see how many times the message box shows.
1. 2. 3. 4. 5. startVal=1 endVal = 5 For var = startVal To endVal show message Next var
Line 1: Loop starts value from 1 Line 2: Loop will end when it reach 5 Line 3: Assign the starting value to var and inform to stop when the var reach endVal Line 4: Execute the loop body
Line 5: Taking next step , if the counter not reach the endVal VB.NET Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As Integer Dim startVal As Integer Dim endVal As Integer startVal = 1 endVal = 5 For var = startVal To endVal MsgBox("Message Box Shows " & var & " Times ") Next var End Sub End Class
When you execute this program , It will show messagebox five time and each time it shows the counter value. If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic.NET provides a keyword Exit to use within the loop body.
For var=startValue To endValue [Step] [loopBody] Contition [Exit For] Next [var]
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim var As Integer Dim startVal As Integer Dim endVal As Integer startVal = 1 endVal = 5 For var = startVal To endVal MsgBox("Message Box Shows " var " Times ") If var = 3 Then Exit For End If Next var End Sub End Class
When you execute the above source code , the program shows the message box only three times
The following VB.NET program shows, how to create a custom exception class and how it is using in the program. Download Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try Dim i As Integer Dim j As Integer Dim k As Integer j = 10 k = 0 i = j / k Catch ex As Exception Throw (New MyCustomException("You can not divide a number by zeo")) End Try End Sub End Class
Public Class MyCustomException Inherits System.ApplicationException Public Sub New(ByVal message As String) MyBase.New(message) MsgBox(message) End Sub End Class
Item : The Item in the group Group : The group containing items LoopBody : The code you want to execute within For Each Loop Let's take a real time example , if you want to display the each character in the website name "HTTP://NET-INFORMATIONS.COM" , it is convenient to use For Each Loop.
1. siteName = "HTTP://NET-INFORMATIONS.COM" 2. For Each singleChar In siteName 3. MsgBox(singleChar) 4. Next
Line 1: Assigning the site name in a variable Line 2: This line is extracting the single item from the group
Line 3: Loop body Line 4: Taking the next step Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim siteName As String Dim singleChar As Char siteName = "HTTP://NET-INFORMATIONS.COM" For Each singleChar In siteName MsgBox(singleChar) Next End Sub End Class
When you execute this program you will get each character of the string in Messagebox.
Line 1: Counter start from 1 Line 2: While loop checking the counter if it is less than or equal to 10 Line 3: Each time the Loop execute the message and show Line 4: Counter increment the value of 1 each time the loop execute Line 5: End of the While End While Loop body Download Source Code Print Source Code
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim counter As Integer counter = 1 While (counter <= 10) MsgBox("Counter Now is : " counter) counter = counter + 1 End While End Sub End Class
When you execute the program 10 times the message shows with counter and exit from the While .. End While loop.
If you pass localhost in GetHostByName return the IP Address of local machine . Download Source Code
Imports System.Net
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim hostname As IPHostEntry = Dns.GetHostByName(TextBox1.Text) Dim ip As IPAddress() = hostname.AddressList TextBox2.Text = ip(0).ToString() End Sub End Class
You can see the basic workflow of .Net Remoting from the above figure. When a client calls the Remote method, the client does not call the methods directly . It receives a proxy to the remote object and is used to invoke the method on the Remote Object. Once the proxy receives the method
call from the Client , it encodes the message using appropriate formatter (Binary Formatter or SOAP Formatter ) according to the Configuration file. After that it sends the call to the Server by using selected Channel (TcpChannel ,HttpChannel). The Server side channel receives the request from the proxy and forwards it to the Server on Remoting system, which locates and invokes the methods on the Remote Object. When the execution of remote method is complete, any results from the call are returned back to the client in the same way. Before an object instance of a Remotable type can be accessed, it must be created and initialized by a process known as Activation. Activation is categorized in two models , they are Clientactivated Objects and Server-activated Objects. Remote Activation The real difference between client-activated and server-activated objects is that a server-activated object is not really created when a client instantiates it. Instead, it is created as needed. By default the .NET Framework ships with two formatters(Binary Formatter or SOAP Formatter ) and two channels(TcpChannel ,HttpChannel). Remote Channels Remote Formatters Formatters and Channel are configured by using Configuration files. It can be easily Configured by using XML-based files. Remote Configuration The .NET Remoting is easy to use and powerful, largely because it is based on the Common Type System (CTS) and the Common Language Runtime (CLR). From the following link , you can
understand .Net Remoting components in detail.
Remotable Type
Any object outside the application domain of the caller application should be considered as Remote Object. A Remote Object that should be derived from MarshalByRefObject Class. Any object can be changed into a Remote Object by deriving it from MarshalByRefObject . Objects without inheriting from MarshalByRefObject are called Non-remotable Objects. The following example creating a Remote Object in VB.Net, RemoteTime , which send the current time to the Client Application using Remoting Framework. The RemoteTime class is derived from MarshalByRefObject and inside the class it has a method getTime() which return the current time from Remote Object. Download Source Code
Imports System Public Class RemoteTime Inherits MarshalByRefObject Private currentTime As String = "" Public Function getTime() As String currentTime = DateTime.Now.ToShortTimeString() Return "Remote Server Time : " & currentTime End Function End Class
Copy and paste the above VB.Net source code into a file and save it as RemoteTime.vb Compile the class RemoteTime.vb into a library using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command: vbc /t:library RemoteTime.vb After you compile the RemoteTime.vb , you will get a file called RemoteTime.dll in the directory which you saved the source file.
for handle the networking protocol and serialization formats and register the Type with the .NET Remoting system, so that it can use the channel to listen for requests for the Type. Channels are Objects that responsible of handling the network protocols and serialization formats. In the following example we are creating a listener application TimeListener . It will act as a listener Object for the Remote Type RemoteTime. The Listener class TimeListener must be able to find the TimeListener.exe.config file to load the configuration for the RemotableType class. Download Source Code
Imports System Imports System.Runtime.Remoting Public Class TimeListener Public Shared Sub Main() RemotingConfiguration.Configure("TimeListener.exe.config") Console.WriteLine("Listening for requests from the Client. Press Enter to exit...") Console.ReadLine() End Sub End Class
Copy and paste the above VB.Net source code into a file and save it as TimeListener.vb. We have to create additional configuration file to provide the communication information to the listener Object. The configuration file is an XML structured file. We can specify the Activation Mode , the Remote Type , Channel , port for communication etc. through the configuration file .
Click here to download TimeListener.exe.config . Compile the class file TimeListener.vb using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command:
vbc /r:RemoteTime.dll TimeListener.vb After you compile the TimeListener.vb , you will get a file called TimeListener.exe in the directory which you saved the source file
Copy and paste the above VB.Net source code into a file and save it as Client.vb. We have to create additional configuration file to provide the communication information to the Client Object. The configuration file is a an XML structured file. We can specify the Remote Type , Channel , port for communication etc. through the configuration file .
Click here to download Client.exe.config . Compile the class file Client.vb using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command: vbc /r:RemoteTime.dll Client.vb After you compile the Client.vb , you will get a file called Client.exe in the directory which you saved the source file
Remoting Configurations
Configuration provides the necessary information to .Net Remoting Framework . We can provide .Net Remoting configuration parameters in two ways. Either we can provide the information to the Server and the Client directly by program coding or through a Machine.config file. Using configuration file give better advantage over coding because the parameters of remote object can be configured without changing any program coding and avoid recompile the source code. Following are the information provided by configuration file : Metadata describing the Remote Type Type of Activation Channels The URL that uniquely identifies the object of that type. We have to provide configuration information to Listener Object and also Client Object . Listener Configuration
Remotable Type
Any object outside the application domain of the caller application should be considered as Remote Object. A Remote Object that should be derived from MarshalByRefObject Class. Any object can be changed into a Remote Object by deriving it from MarshalByRefObject . Objects without inheriting from MarshalByRefObject are called Non-remotable Objects. The following example creating a Remote Object in VB.Net, RemoteTime , which send the current time to the Client Application using Remoting Framework. The RemoteTime class is derived from MarshalByRefObject and inside the class it has a method getTime() which return the current time from Remote Object. Download Source Code
Imports System Public Class RemoteTime Inherits MarshalByRefObject Private currentTime As String = ""
Public Function getTime() As String currentTime = DateTime.Now.ToShortTimeString() Return "Remote Server Time : " & currentTime End Function End Class
Copy and paste the above VB.Net source code into a file and save it as RemoteTime.vb Compile the class RemoteTime.vb into a library using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command: vbc /t:library RemoteTime.vb After you compile the RemoteTime.vb , you will get a file called RemoteTime.dll in the directory which you saved the source file.
Compile these VB.Net class files using the command-line tools that ship with the .NET Framework SDK. vbc /t:library RemoteTime.vb vbc /r:RemoteTime.dll TimeListener.vb vbc /r:RemoteTime.dll Client.vb Note: You have to provide the physical path of each source files when you compile the source code , for example : if the source code files are in the folder c:\SRC , you have to give path like vbc /r:c:\SRC\RemoteTime.dll c:\SRC\TimeListener.vb After you complied the VB.Net source code files, you will get additional three files in the SRC folder. They are : RemoteTime.dll TimeListener.exe Client.exe To run the application Create two new folders and give the name like Server and Client respectively. Copy RemoteTime.dll , TimeListener.exe and TimeListener.exe.config to the Server folder. Copy RemoteTime.dll , Client.exe and Client.exe.config to the Client folder. Open a command prompt on Server folder and type TimeListener Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..." Open a command prompt on Client folder and type Client. Then you will get the current time from remote Object. Now you have done your first .Net Remoting VB.Net project successfully . Try to explore more on Remoting ...
object, and return the results to the client. The Client Application have to register for the Remote Type also. Here in the Client application in VB.Net , creating an instance of the Remote Type, RemoteTime Object , and call the method getTime() . Aditionally it uses the configuration file Client.exe.config for the communication information for the Remoting Framework. Download Source Code
Imports System Imports System.Runtime.Remoting Public Class Client Public Shared Sub Main() RemotingConfiguration.Configure("Client.exe.config") Dim remoteTimeObject As New RemoteTime() Console.WriteLine(remoteTimeObject.getTime()) End Sub End Class
Copy and paste the above VB.Net source code into a file and save it as Client.vb. We have to create additional configuration file to provide the communication information to the Client Object. The configuration file is a an XML structured file. We can specify the Remote Type , Channel , port for communication etc. through the configuration file .
Click here to download Client.exe.config . Compile the class file Client.vb using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command: vbc /r:RemoteTime.dll Client.vb
After you compile the Client.vb , you will get a file called Client.exe in the directory which you saved the source file
Copy and paste the above VB.Net source code into a file and save it as TimeListener.vb. We have to create additional configuration file to provide the communication information to the listener Object. The configuration file is an XML structured file. We can specify the Activation Mode , the Remote Type , Channel , port for communication etc. through the configuration file .
Click here to download TimeListener.exe.config . Compile the class file TimeListener.vb using the command-line tools that ship with the .NET Framework SDK. At the command prompt in the directory in which you saved the file, type the following command: vbc /r:RemoteTime.dll TimeListener.vb After you compile the TimeListener.vb , you will get a file called TimeListener.exe in the directory which you saved the source file
Remoting Activation
The .Net Remoting framework supports Server and Client activation of Remote Objects. Before an Object instance of a Remotable type can be accessed, it must be created and initialized by Activation process. There are commonly two types of activation modes : Server Activation and Client Activation mode. Server activation is normally used when a Remote objects is not required to maintain any state between method calls. Client Activated objects are instantiated from the client, and the client manages the lifetime of the Remote Object by using a lease-based system provided for that purpose. SingleCall Objects and Singleton Objects belong to Server Activation mode. For SingleCall objects the server will create a single object, execute the method, and destroy the object again. On the other hand with Singleton mode only one object is created at all. Singleton objects can be used to share information between multiple clients. The real distinction between Client Activated and Server Activated object is that a server-activated object is not really created when a client instantiates it. Instead, it is created as needed.
Remoting Channel
In .Net Remoting Channels are used to transport messages to and from the Remote Objects. Channels are Objects that responsible of handling the network protocols and serialization formats. In .Net Remoting channel can be implement either by calling the method ChannelServices.RegisterChannel or by using configuration file. Channels should be registered before objects are registered.
When a channel is registered, it automatically starts listening for client requests at the specified port. At least one channel must be registered with the remoting framework before a Remote object can be called. There are two types of Channels available in .Net Remote Framework: HTTP channel and TCP channel. The HTTP
channel transports messages to and from remote objects using the SOAP protocol. The TCP channel uses a binary formatter to serialize all messages to a binary stream and transport the stream to the target URI using the TCP protocol.
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim writer As New XmlTextWriter("product.xml", System.Text.Encoding.UTF8) writer.WriteStartDocument(True) writer.Formatting = Formatting.Indented writer.Indentation = 2 writer.WriteStartElement("Table") createNode(1, "Product 1", "1000", writer) createNode(2, "Product 2", "2000", writer) createNode(3, "Product 3", "3000", writer) createNode(4, "Product 4", "4000", writer) writer.WriteEndElement() writer.WriteEndDocument() writer.Close() End Sub Private Sub createNode(ByVal pID As String, ByVal pName As String, ByVal pPrice As String, ByVal writer As XmlTextWriter) writer.WriteStartElement("Product") writer.WriteStartElement("Product_id") writer.WriteString(pID) writer.WriteEndElement() writer.WriteStartElement("Product_name") writer.WriteString(pName) writer.WriteEndElement() writer.WriteStartElement("Product_price") writer.WriteString(pPrice) writer.WriteEndElement() writer.WriteEndElement() End Sub End Class
The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . These classes are stored in the namespaces like System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, System.Xml.Xsl etc. The Dataset in ADO.NET uses XML as its internal storage format. You can use any text editor to create an XML file . More over XML files are readable by humans as well as computers. From the following links you can see how to use XML in VB.NET.
Imports System.Xml Imports System.IO Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click Dim xmldoc As New XmlDataDocument() Dim xmlnode As XmlNodeList Dim i As Integer Dim str As String Dim fs As New FileStream("products.xml", FileMode.Open, FileAccess.Read) xmldoc.Load(fs) xmlnode = xmldoc.GetElementsByTagName("Product") For i = 0 To xmlnode.Count - 1 xmlnode(i).ChildNodes.Item(0).InnerText.Trim() str = xmlnode(i).ChildNodes.Item(0).InnerText.Trim() & " | " & xmlnode(i).ChildNodes.Item(1).InnerText.Trim() & " | " & xmlnode(i).ChildNodes.Item(2).InnerText.Trim() MsgBox(str) Next End Sub End Class
fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" ds.WriteXml("Product.xml") MsgBox("Done") End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class
Imports System.Xml Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet ds.ReadXml(xmlFile) Dim i As Integer For i = 0 To ds.Tables(0).Rows.Count - 1 MsgBox(ds.Tables(0).Rows(i).Item(1)) Next End Sub End Class
Imports System.Xml Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim adapter As SqlDataAdapter Dim ds As New DataSet Dim sql As String connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password" connection = New SqlConnection(connetionString) sql = "select * from Product" Try connection.Open() adapter = New SqlDataAdapter(sql, connection) adapter.Fill(ds) connection.Close() ds.WriteXml("Product.xml") MsgBox("Done") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class
and pass the XmlReader as argument of Dataset. By using the Dataset , search the product Product2 in the file Product.XML with the help of DataView. Download Source Code Print Source Code
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0)) dv.Sort = "Product_Name" Dim index As Integer = dv.Find("Product2") If index = -1 Then MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_Name").ToString() & " ("Product_Price").ToString()) End If End Sub
Imports System.Xml Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet Dim dv As DataView ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0), "Product_price > = 3000", "Product_Name", DataViewRowState.CurrentRows) dv.ToTable().WriteXml("Result.xml") MsgBox("Done") End Sub End Class
Imports System.Xml Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adpter As New SqlDataAdapter Dim ds As New DataSet Dim xmlFile As XmlReader Dim sql As String Dim product_ID As Integer Dim Product_Name As String Dim product_Price As Double connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password" connection = New SqlConnection(connetionString)
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) ds.ReadXml(xmlFile) Dim i As Integer connection.Open() For i = 0 To ds.Tables(0).Rows.Count - 1 product_ID = Convert.ToInt32(ds.Tables(0).Rows(i).Item(0)) Product_Name = ds.Tables(0).Rows(i).Item(1) product_Price = Convert.ToDouble(ds.Tables(0).Rows(i).Item(2)) sql = "insert into Product values(" & product_ID & ",'" & Product_Name & "'," & product_Price & ")" command = New SqlCommand(sql, connection) adpter.InsertCommand = command adpter.InsertCommand.ExecuteNonQuery() Next connection.Close() End Sub End Class
You have to pass necessary database connection information to connection string. Click here to download the input file product.xml
Imports System.Xml Imports System.Data Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmlFile As XmlReader xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings()) Dim ds As New DataSet ds.ReadXml(xmlFile) DataGridView1.DataSource = ds.Tables(0) End Sub End Class
XML Serialization is the process of serializing a .Net Object to the form of XML or from an XML to .Net Object. The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa. This is the process of converting an object into a form that can be readily transported. During XML serialization, only the public properties and fields of an object are serialized. The following links gives you more details about XML Serialization and De-serialization.
Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet dt = New DataTable() dt.Columns.Add(New DataColumn("Product_ID", Type.GetType("System.Int32"))) dt.Columns.Add(New DataColumn("Product_Name", Type.GetType("System.String"))) dt.Columns.Add(New DataColumn("product_Price", Type.GetType("System.Int32"))) fillRows(1, "product1", 9999) fillRows(2, "product2", 2222) fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" Dim serialWriter As StreamWriter serialWriter = New StreamWriter("serialXML.xml") Dim xmlWriter As New XmlSerializer(ds.GetType()) xmlWriter.Serialize(serialWriter, ds) serialWriter.Close() ds.Clear() End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow()
dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class
Imports System.Xml.Serialization Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType) Dim readStream As FileStream = New FileStream("serialXML.xml", FileMode.Open) ds = CType(xmlSerializer.Deserialize(readStream), DataSet) readStream.Close() DataGridView1.DataSource = ds.Tables(0) End Sub End Class
Public Class Form1 Dim dt As DataTable Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet dt = New DataTable() dt.Columns.Add(New DataColumn("Product_ID", Type.GetType("System.Int32"))) dt.Columns.Add(New DataColumn("Product_Name", Type.GetType("System.String"))) dt.Columns.Add(New DataColumn("product_Price", Type.GetType("System.Int32"))) fillRows(1, "product1", 9999) fillRows(2, "product2", 2222) fillRows(3, "product3", 3333) fillRows(4, "product4", 4444) ds.Tables.Add(dt) ds.Tables(0).TableName = "product" Dim serialWriter As StreamWriter serialWriter = New StreamWriter("serialXML.xml") Dim xmlWriter As New XmlSerializer(ds.GetType()) xmlWriter.Serialize(serialWriter, ds) serialWriter.Close() ds.Clear() End Sub Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal pPrice As Integer) Dim dr As DataRow dr = dt.NewRow() dr("Product_ID") = pID dr("Product_Name") = pName dr("product_Price") = pPrice dt.Rows.Add(dr) End Sub End Class
Imports System.Xml.Serialization Imports System.io Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ds As New DataSet Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType) Dim readStream As FileStream = New FileStream("serialXML.xml", FileMode.Open) ds = CType(xmlSerializer.Deserialize(readStream), DataSet) readStream.Close() DataGridView1.DataSource = ds.Tables(0) End Sub End Class