Friday, 3 March 2017

BCA VB.Net Question Answer

Explain Redim statement. what is the use of preserve statement
Dynamic Arrays can resize the capability of the Array at runtime .when you are in a situation that you do not know exactly the number of elements to store in array while you making the program. In that situations we are using Dynamic Array .
Initial declaration

Dim scores() As Integer

Resizing

ReDimscores(1)

If you want to keep the existing items in the Array , you can use the keyword Preserve .

ReDim Preserve scores(2)

In this case the Array dynamically allocate one more String value and keep the existing values.
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

        For i = 0 To scores.Length - 1
MsgBox(scores(i))
        Next
    End Sub
End Class


Shortnote on Menu
The MenuStrip control represents the container for the menu structure.
The MenuStrip control works as the top-level container for the menu structure. The ToolStripMenuItem class and the ToolStripDropDownMenu class provide the functionalities to create menu items, sub menus and drop-down menus.
After drag the Menustrip on your form you can directly create the menu items by type a value into the "Type Here" box on the menubar part of your form.
If you need a separator bar , right click on your menu then go to insert->Separator.
After creating the Menu on the form , you have to double click on each menu item and write the programs there depends on your requirements. The following Vb.Net program shows how to show a messagebox when clicking a menu item


Public Class Form1

    Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1ToolStripMenuItem.Click

MsgBox("You are selected MenuItem_1")

    End Sub

End Class

The following are some of the commonly used properties of the MenuStrip control:
CanOverflow
Gets or sets a value indicating whether the MenuStrip supports overflow functionality.
GripStyle
Gets or sets the visibility of the grip used to reposition the control.
MdiWindowListItem
Gets or sets the ToolStripMenuItem that is used to display a list of Multiple-document interface (MDI) child forms.
ShowItemToolTips
Gets or sets a value indicating whether ToolTips are shown for the MenuStrip.
Stretch
Gets or sets a value indicating whether the MenuStrip stretches from end to end in its container.

The following are some of the commonly used events of the MenuStrip control:
MenuActivate
Occurs when the user accesses the menu with the keyboard or mouse.
MenuDeactivate

Occurs when the MenuStrip is deactivated.

Modal and Modeless Dialog Boxes
Dialog boxes are either modal or modeless. A modal dialog box must be closed (hidden or unloaded) before you can continue working with the rest of the application. For example, a dialog box is modal if it requires you to click OK or Cancel before you can switch to another form or dialog box.
The About dialog box in Visual Basic is modal. Dialog boxes that display important messages should always be modal — that is, the user should always be required to close the dialog box or respond to its message before proceeding.
Modeless dialog boxes let you shift the focus between the dialog box and another form without having to close the dialog box. You can continue to work elsewhere in the current application while the dialog box is displayed. Modeless dialog boxes are rare. From the Edit menu, the Find dialog box in Visual Basic is an example of a modeless dialog box. Use modeless dialog boxes to display frequently used commands or information.
To display a form as a modal dialog box
Use the Show method with a style argument of vbModal (a constant for the value 1).
For example:
' DisplayfrmAbout as a modal dialog.
frmAbout.ShowvbModal

To display a form as a modeless dialog box
Use the Show method without a style argument.
For example:
' DisplayfrmAbout as a modeless dialog.
frmAbout.Show
ListBox
The ListBox represents a Windows control to display a list of items to a user. A user can select single or multiple item from the list. It allows the programmer to add or remove items at design time by using the properties window or at the runtime.
You can populate the list box items either from the properties window or at runtime.
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
ContextMenu
The ContextMenuStrip control represents a shortcut menu that pops up over controls, usually when you right click them. They appear in context of some specific controls, so are called context menus. For example, Cut, Copy or Paste options.
This control associates the context menu with other menu items by setting that menu item's ContextMenuStrip property to the ContextMenuStrip control you designed.
Context menu items can also be disabled, hidden or deleted. You can also show a context menu with the help of the Show method of the ContextMenuStrip control.
Exception(Structured Error handling)
Exceptions are the occurrence of some condition that changes the normal flow of execution. For ex: you programme run out of memory, file does not exist in the given path, network connections are dropped etc. More specifically for better understanding, we can say it as Runtime Errors.
In .NET languages, Structured Exceptions handling is a fundamental part of Common Language Runtime. It has a number of advantages over the On Error statements provided in previous versions of Visual Basic. All exceptions in the Common Language Runtime are derived from a single base class, also you can create your own custom Exception classes. You can create an Exception class that inherits from Exception class.
You can handle Exceptions using Try..Catch statement.

  Try
          code
          exit from Try
  Catch [Exception [As Type]]
          code - if the exception occurred this code will execute
          exit from Catch

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

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

On Error GoTo(Unstructured Error handling)
On Error GoTo statements is an example of Vb.Net's Unstructured Exception Handling. VB.NET has two types of Exception handling. Structured Error Handling and Unstructured Error handling.

Error GoTo redirect the flow of the program in a given location.

On Error Resume Next - whenever an error occurred in runtime, skip the statement and continue execution on following statements.

Take a look at the following program

VB.NET Source Code

  Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e AsSystem.EventArgs) Handles Button1.Click
        Dim result As Integer
        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 "
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
        On Error GoTonextstep
        Dim result As Integer
        Dim num As Integer
num = 100
        result = num / 0
nextstep:
MsgBox("Control Here")
    End Sub
End Class

VB.NET using Try..Catch statement for Structured Error handling and On Error GoTo statement is using for Unstructured Error handling.

Procedure in VB.Net
A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.
The Sub statement is used to declare the name, parameter and the body of a sub procedure. The syntax for the Sub statement is:
[Modifiers] Sub SubName [(ParameterList)]
    [Statements]
End Sub
Where,
Modifiers: specify the access level of the procedure; possible values are: Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
SubName: indicates the name of the Sub/procedure
ParameterList: specifies the list of the parameters

The syntax for each parameter in the parameter list is as follows:
[Optional] [ByVal | ByRef] [ParamArray] parametername As datatype 
When control passes to the procedure, each parameter is treated as a local variable. 

The syntax for a call to a Sub procedure is as follows:
[Call] subname[(argumentlist)] 

Example
Public sub result(ByVal x As Int, ByVal y As Int)
      Dim temp As Integer
      temp = x ' save the value of x
      x = y    ' put y into x
      y = temp 'put temp into y
      msgbox(“value of x” & x &”value of y” & y )
End Sub


A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. The Function procedure performs a task and then returns control to the calling code. When it returns control, it also returns a value to the calling code.
Each time the procedure is called, its statements run, starting with the first executable statement after the Function statement and ending with the first End Function, Exit Function, or Return statement encountered.
You can define a Function procedure in a module, class, or structure. It is Public by default, which means you can call it from anywhere in your application that has access to the module, class, or structure in which you defined it.
A Function procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code.
Syntax:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
    [Statements]
End Function

Every Function procedure has a data type, just as every variable does. This data type is specified by the As clause in the Function statement, and it determines the data type of the value the function returns to the calling code. 
For Example:
Function findSqrt(ByVal radicand As Single) As Single
End Function

The value a Function procedure sends back to the calling code is called its return value.
Function FunctionName [(ParameterList)] As ReturnType
    Return Expression
End Function

RichtextBox
A RichTextBox control is an advanced text box that provides text editing and advanced formatting features including loading rich text format (RTF) files.
The RichTextBox can load and save its contents in plain text (.txt) files or in Rich Text Format (.rtf) files
Text always wraps in a RichTextBox. If you do not want text to wrap then set the PageWidth on the FlowDocument to be larger than the width of the RichTextBox
Scrollbars are not visible on a RichTextBox by default. To make a scrollbar visible, set the VerticalScrollBarVisibility property to Visible or Auto.

RichTextBox Properties
Name
Name property represents a unique name of a RichTextBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a RichTextBox control.
dynamicRichTextBox.Name = "DynamicRichTextBox"

Text and TextLength
Text property of a RichTextBox represents the current text of a RichTextBox control. The TextLength property returns the length of a RichTextBox contents..
dynamicRichTextBox.Text = "I am Dynamic RichTextBox"
Dim len As Integer = dynamicRichTextBox.TextLength

Append Text
One way to append text to a RichTextBox is simply set Text property to current text plus new text you would want to append something like this.
RichTextBox1.Text += " Appended text"
RichTextBox also has the ApendText method to do the same. The AppendText method appends text at the end of a RichTextBox
RichTextBox1.AppendText(" Appended text")

WordWrap
If WordWrap property is true, the text in the RichTextBox control automatically wraps to the next line if required. If this property is set to true, horizontal scroll bars are not displayed regardless of the ScrollBars property setting.
dynamicRichTextBox.WordWrap = True

ScrollBars
A Multiline RichTextBox control can have scrollbars. The ScrollBars property of RichTextBox control is used to show scrollbars on a control.
dynamicRichTextBox.ScrollBars = RichTextBoxScrollBars.Both

Methods
Appends a string to the contents of a text control.

Copies the current selection of the text editing control to the Clipboard.

Removes the current selection from the text editing control and copies it to the Clipboard.

Redoes the most recent undo command. In other words, redoes the most recent undo unit on the undo stack

Undoes the most recent undo command. In other words, undoes the most recent undo unit on the undo stack.

Selects all the contents of the text editing control.

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
   
Array
An array is a set of values that are logically related to each other.
By using an array, you can refer to these related values by the same name, and use a number that’s called an index or subscript to tell them apart.
The individual values are called the elements of the array. They’re contiguous from index 0 through the highest index value.
The following example declares an array variable
Dim students(6) As Integer
Dim numbers = New Integer() {1, 2, 4, 8} //populating array with initial value

You can access each location in an array by using an index of type Integer. You can store and retrieve values in an array by referencing each array location by using its index enclosed in parentheses.
array.Length:We can use array.Length to find the length of an Array.
You can define the size of an array several ways. You can supply the size when the array is declared
Dim percentage(10) As Double 
Dim val(2, 2, 4, 10) As Short 
Dim inquiries(20)()() As Byte

If you have an existing array, you can redefine its size by using the Redim statement. You can specify that the Redim statement should keep the values that are in the array, or you can specify that it create an empty array. The following example shows different uses of the Redim statement to modify the size of an existing array.

' Assign a new array size and retain the current element values. 
ReDim Preserve cargoWeights(20)
' Assign a new array size and retain only the first five element values. 
ReDim Preserve cargoWeights(4)
' Assign a new array size and discard all current element values. 
ReDim cargoWeights(15)
                           
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim array As Integer() = New Integer(3) {}
        array(0) = 10
        array(1) = 20
        array(2) = 30
        array(3) = 40
        For i As Integer = 0 To array.Length - 1
            MessageBox.Show(array(i))
        Next
    End Sub
End Class

String Array
Declaring and Initializing a String Array
Dim week(6) As String
The above Vb.Net statements means that , an Array named as week declared as a String type and it can have the capability of seven String type values.
week(0) = "Sunday"
week(1) = "Monday"
In the above statement, we initialize the values to the String Array.week(0) = "Sunday" means , we initialize the first value of Array as "Sunday" ,
Dim weekName as String = week(1)
We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week Array.
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


ForEach loop with Arrays
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim array As Integer() = {10, 30, 50}
        'array declaration
        For Each element As Integer In array
            MsgBox(element)
        Next
    End Sub
End Class


Collection
Visual Basic also provides a Collection class, with which you can define and create your own collections. Like a form's Controls collection.  
Dim coll As New Microsoft.VisualBasic.Collection()

Once you have created a collection, you can do any of the following:
  • Add an element with the Add method.
    • object.Add(Item, Key [, {Before | After}])
  • Remove an element with the Remove method.
    • object.Remove({Index | Key})
  • Remove all elements with the Clear method.
    • object.Clear()
  • Find out how many elements the collection contains with the Count property.
  • Check whether a specific element is present with the Contains method.
  • Return a specific element from the collection with the Item property.
  • Iterate through the entire collection with the For Each...Next Statement (Visual Basic).

It has an Add method for putting items into the collection and a Remove method for taking items out.
Collection class also provides you with the built-in functionality to loop through elements using For Each...Next and to retrieve elements by index. 
Instances of the Visual Basic Collection class allow you to access an item using either a numeric index or a String key. You can add items to Visual Basic Collection objects either with or without specifying a key. If you add an item without a key, you must use its numeric index to access it.

Various Collection Classes and Their Usage
The following are the various commonly used classes of the System.Collection namespace. Click the following links to check their details.

Class
Description and Useage
It represents ordered collection of an object that can beindexed individually.
It is basically an alternative to an array. However, unlike array, you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list.
It uses a key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.
It uses a key as well as an index to access the items in a list.
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.
It represents a last-in, first out collection of object.
It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item, and when you remove it, it is called popping the item.
It represents a first-in, first out collection of object.
It is used when you need a first-in, first-out access of items. When you add an item in the list, it is calledenqueue, and when you remove an item, it is calleddeque.
It represents an array of the binary representation using the values 1 and 0.
It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero.

//Declaration
Dim Coll As New Microsoft.VisualBasic.Collection()

//Insert element in collection
Dim item1, item2, item3, item4 As String
item1 = "Items"
item2 = "In"
item3 = "A"
item4 = "Collection"
Coll.Add(item1, "firstkey")
Coll.Add(item2, "secondkey")
Coll.Add(item3, "thirdkey")
Coll.Add(item4, "fourthkey")

// Remove the first element of the Visual Basic collection.
Coll.Remove(1)
//Remove the element with the key "secondkey".
Coll.Remove("secondkey")

D//Display All
For Each aString in Coll
    If aString = "Collection" Then
        MsgBox(aString)
    End If
Next aString


Different between Array and Collection
Array
Collection
An array stores a fixed-size sequential collection of elements of the same type
Collection classes are specialized classes for data storage and retrieval. These classes provide support for arraylist, stacks, queues, lists, and hash tables.
Arrays are generally faster than collections
Collection is slower than array
The  System.Array is the base class for all the arrays in VB.Net
Base class is System.Collection namespace
Arrays use less memory
collection use more memory
Array is Fixed in Size
Collection is Grow able in nature
Dim students(6) As Integer

Dim Coll As New Microsoft.VisualBasic.Collection()

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx












Option Strict On-Off
Option Strict is prevents program from automatic variable conversions, that is implicit data type conversions.
Option Strict [On Off]
By default Option Strict is Off
From the following example you can understand the use of Option Strict.
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 longNum As Long
                   Dim intNum As Integer
                   longNum = 12345
                   intNum = longNum
                   MsgBox(intNum)
          End Sub
  End Class


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.

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.

VB.NET Option Explicit [On | Off]
Option Explicit statement ensures whether the compiler requires all variables to be explicitly declared or not before it use in the program.
Option Explicit [On Off]
The Option Explicit has two modes. On and Off mode. If Option Explicit mode in ON, you have to declare all the variable before you use it in the program . If not, it will generate a compile-time error whenever a variable that has not been declared is encountered .If the Option Explicit mode is OFF , Vb.Net automatically create a variable whenever it sees a variable without proper declaration.
By default the Option Explicit is On
With the Option Explicit On , you can reduce the possible errors that result from misspelled variable names. Because in Option Explicit On mode you have to declare each variable in the program for storing data.
Take a look at the following programs, it will give you a clear picture of Option Explicit.
The following program is a normal vb.net program , so the default mode of Option Explicit On is using. The default is Option Explicit On , so we do not need to put it in the source code.
  Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Dim someVariable As String
        someVariable = "Option Explicit ON"
        MsgBox(someVariable)
    End Sub
  End Class
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 Off

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 OFF"
        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. 

VB.NET Access Specifiers
Access Specifiers describes as the scope of accessibility of an Object and its members. We can control the scope of the member object of a class using access specifiers. We are using access specifiers for providing security of our applications.

Visual Basic .Net provide five access specifies, they are as follows:
Public, Private, Protected, Friend and ProtectedFriend .
Public:
Public is the most common access specifier. It can be access from anywhere, that means there is no restriction on accessibility. The scope of the accessibility is inside class also in outside the class.
Private:
The scope of the accessibility is limited only inside the classes in which they are decleared. The Private members cannot be accessed outside the class and it is the least permissive access level.
Protected:
The scope of accessibility is limited within the class and the classses derived (Inherited )from this class.
Friend:
The Friend access specifier can access within the program that contain its declarations and also access within the same assembly level. You can use friend instead of Dim keyword.
ProtectedFriend:
ProtectedFriend is same access lebels of both Protected and Friend. It can access anywhere in the same assembly and in the same class also the classes inherited from the same class.


ADO
ADO.Net
ADO stands for ActiveX Data Objects and it relies on COM
ADO.NET relies on managed providers defined by the .NET CLR (Common Language Runtime)
ADO fits all connections to all types of data sources into a single Connection object
ADO.NET can have separate Objects that represent connections to different data sources
ADO allows you to create client side cursors only
ADO.NET gives you the choice of either using client side or server side cursors
ADO recordsets can hold data from one data source at a time
ADO.Net datasets can hold data from various sources and integrate the data and write it back to one or several data sources
ADO objects communicate in binary mode
ADO.NET uses XML for passing the data
ADO does not have method like executescalar
ADO.NET command object has an ExecuteScalar method





Dataset
Datareader
DataSet object can contain multiple rowsets from the same data source as well as from the relationships between them
DataReader provides forward-only and read-only access to data
Dataset is a disconnected architecture
Datareader is connected architecture
Dataset can persist data
Datareader can not persist data
Support  Disconnected architecture
Connection needs to be maintained all the time
Can traverse data in any order front, back
Can traverse only forward
Data can be manipulated within the dataset
It is read only therefore, data cannot be manipulated
More expensive than datareader as it stores multiple rows at the same time
It is less costly because it stores one row at a time