0% found this document useful (0 votes)
23 views

C#&.Net notes unit 3&4

Gtyhjjj Sjsj Jsjsjssk Jsjsjsjk

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

C#&.Net notes unit 3&4

Gtyhjjj Sjsj Jsjsjssk Jsjsjsjk

Uploaded by

akshayamith887
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

II BCA C# and Dot Net Framework

UNIT-3

Two Mark Questions


1. List any four datatypes used in VB.net?

= Long, Byte, Char, DOUBLE, Date, Time, Boolean etc

2. Write the syntax of switch statement?

=Select [ Case ] expression

[ Case expressionlist

[ statements ] ]

[ Case Else

[ elsestatements ] ]

End Select

expression − is an expression that must evaluate to any of the elementary data type in
VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte,
Short, Single, String, UInteger, ULong, and UShort.
• expressionlist − List of expression clauses representing match values
for expression. Multiple expression clauses are separated by commas.
• statements − statements following Case that run if the select expression matches
any clause in expressionlist.
• else statements − statements following Case Else that run if the select expression
does not match any clause in the expressionlist of any of the Case statements.

3. Differentiate for…next and for…each …next loops?

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

For Each...Next:

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

4. Write the usage of Dim and Redim keywords.

= Redim :You can use the ReDim statement to change the size of one or more dimensions
of an array that has already been declared.

Dim : Declares and allocates storage space for one or more variables.
II BCA C# and Dot Net Framework

5. Differentiate Sub procedures and functions.

=Sub Procedures: A subprocedure is a group of VB.NET statements. It begins with a Sub


keyword and ends with End Sub keywords. A subprocedure is also called a subroutine.

Function Procedures:

A function procedure is a group of VB.NET statements. It begins with a Function keyword


and ends with an End Function keyword. It is generally used to perform a task and return
a value back to the calling code.

6. What do you mean by events?

Ans: An event is a signal that informs an application that something important has
occurred. For example, when a user clicks a control on a form, the form can raise a Click.

7. Write the syntax of while loop?

= While condition

[ statements ]

[ Continue While ]

[ statements ]

[ Exit While ]

[ statements ]

End While

8. What do you mean by methods?

= A method is an action that an object can perform. For example, Add is a method of the
ComboBox object, because it adds a new entry to a combo box.

9. Write the purpose of Show and Hide methods of VB.net Forms?


II BCA C# and Dot Net Framework

=Show Method: This method is used to display the form on top of all other windows even
if it is loaded or not loaded into the memory.

Hide Method: This method hides a form object from the screen, still with the object being
loaded in the memory.

10. Specify any four values of FormBorder style property

Ans: The border-style property sets the style of an element's four borders. This property
can have from one to four values.
...
border-style: dotted solid double dashed;
1. top border is dotted.
2. right border is solid.
3. bottom border is double.
4. left border is dashed.
11. What is the use of Window state property? Specify the values.

=Gets or sets a value that indicates whether a window is restored, minimized, or


maximized.

Property Value

WindowState:

A WindowState that determines whether a window is restored, minimized, or maximized.


The default is Normal (restored).

12. What is MDI form? Mention its advantages.?

=Multiple-document interface (MDI) applications enable to display multiple documents at


the same time, with each document displayed in its own window. MDI applications often
have a Window menu item with submenus for switching between windows or documents.

13. Differentiate GotFocus and LostFocus events?

=1.LostFocus: Occurs when the form loses focus.

2.GotFocus: Occurs when the form receives focus.

14. How do you make a textbox non editable during run time?

=If the content of the textbox should not be edited by the user, then the textbox should be
made read only.
II BCA C# and Dot Net Framework

Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As


System.EventArgs) Handles Form1.Load

TextBox1.ReadOnly = True

End Sub

15. Differentiate textbox and labels?

=a)Textboxes need to be set as readonly whereas in labels you dont need to do that.

b)Even when I set the textboxes as read only the Cursor is still visible whereas in Label it
isn't.

16. Write the code to create a TextBox.?

Ans:

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As


System.EventArgs) Handles Butt on1.Click

Dim TextBox1 As New TextBox()

End Sub

17. What is the use of Autosize property of label?

Ans:

Gets or sets a value specifying if the control should be automattically resized to display all
its contents.

18. What is the use of HideSelection property of the text box.?

Ans: Gets or sets a value indicating whether the selected text in the text box control
remains highlighted when the control loses focus.

19. Specify the various ways of aligning the text in labels?

=1. Bottom left :Vertically aligned at the bottom, and horizontally aligned on the left.

2.Bottom right :Vertically aligned at the bottom,and horizontally aligned on the right.
II BCA C# and Dot Net Framework

3. MiddleLeft: Vertically aligned at the middle,and horizontally aligned on the left.

4.Middl right :Vertically aligned at the middle,and horizontally aligned on the right.

20.How do you add picture to a button?

Ans:

Images can be added to buttons at design time and at run time. At design time, you only
need to set the Image property in the Properties window to an image file. At run time, you
can do the same thing if you use the Image class's FromFile class method and assign the
resulting Image Object to the button's Image property.

21. Give the code to create button at runtime.


Private Sub buttonCreateButton_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles buttonCreateButton.Click
Dim btn As New Button
btn.Name = "DynamicButton"
btn.Size = New Size(148, 23)
btn.Location = New Point(53, 39)
btn.Text = "Click me"
GroupBox1.Controls.Add(btn)
End Sub

22. Describe the items and multicoloumn properties of a ListBox.

Items :Gets the items of the list box.


MultiColumn: Gets or sets a value indicating whether the list box supports multiple
columns.

23. How do you determine the selected item in a list/combo box?


The object that is the currently selected item or null if there is no currently selected item.

private void showSelectedButton_Click(object sender, System.EventArgs e) {


int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;

MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +


"Index: " + selectedIndex.ToString());
II BCA C# and Dot Net Framework

24. How to Clear a combo box.


By using following code we can clear all items from ComboBox

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As


System.EventArgs) Handles Butt on1.Click

combobox.Items.Clear()

End Sub

25. How to Get the number of items in a combo box?


Ans: By using following code we can count all items from ComboBox
var count = comboBox.Items.Count;
Or
You should reference Count of the Items property.
myComboBox.Items.Count

26. Differentiate Listbox and combobox.


List Box :
1. Occupies more space but shows more than one value.
2. We can select multiple items.
3. we can use checkboxes with in the list box.

Combo Box:
1. Occupies less space but shows only one value for visibility
2. Multiple select is not possible
3. can't use checkboxes within combo boxes

27. How to Create Simple Drop-down, Drop-down List Combo Boxes.

Ans: The ComboBox control is used to display a drop-down list of various items. It is a
combination of a text box in which the user enters an item and a drop-down list from
which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping
it on the form.

28. Mention the purpose of Progressbar and Trackbar.


Ans:
Progress Bar : It is used to provide visual feedback to your users about the status of
some task. It shows a bar that fills in from left to right as the operation progresses. The
main properties of a progress bar are Value, Maximum and Minimum. The ProgressBar
control is typically used when an application status.
II BCA C# and Dot Net Framework

Trackbar: The Track Bar is a horizontal slider that enables the user to select values on
a bar by moving the slider. The tick marks are spaced at regular intervals called the tick
frequency. The user can set the Maximum and Minimum values on the TrackBar, it is also
called as Slide Control.

29. How to add collection of objects in a listbox at once?


Ans: To add items to a ListBox, select the ListBox control and get to the properties
window, for the properties of this control. Click the ellipses (...) button next to the Items
property. This opens the String Collection Editor dialog box, where you can enter the
values one at a line.
30. List any two public properties of HScrollBar

Maximum
Gets or sets the upper limit of values of the scrollable range.
Minimum
Gets or sets the lower limit of values of the scrollable range.

31. List any two public properties of Scrollbar


LargeChange
Gets or sets a value to be added to or subtracted from the Value property when the scroll
box is moved a large distance.
Maximum
Gets or sets the upper limit of values of the scrollable range.
Minimum
Gets or sets the lower limit of values of the scrollable range.
SmallChange
Gets or sets the value to be added to or subtracted from the Value property when the scroll
box is moved a small distance.
Value
Gets or sets a numeric value that represents the current position of the scroll box on the
scroll bar control.

32. How to set Scroll Bars' Minimum and Maximum Values?

Step 1: The first step is to drag the HScrollBar and VScrollBar control from the toolbox
and drop it on to the form.

Step 2: Once the ScrollBar is added to the form, we can set minimum and maximum
properties of the ScrollBar by clicking on the HScrollBar and VScrollBar control.
II BCA C# and Dot Net Framework

Or by code

Public Class ScrollBar


Private Sub ScrollBar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.AutoScroll = True
Me.VScrollBar1.Minimum = 0
Me.VScrollBar1.Maximum = 100
Me.VScrollBar1.Value = 0

Me.HScrollBar1.Minimum = 0
Me.HScrollBar1.Maximum = 100
Me.HScrollBar1.Value = 35
End Sub
End Class

33. Write a note on Scroll Bars' LargeChange SmallChange property

The user can set the LargeChange and SmallChange values to any integer in the range
of 0 to 100.

This will uses the MaxLength property to restrict the number of characters entered for
the LargeChange and SmallChange values.

34. How to get & set Scroll Bar's Current Value ?


Gets or sets a numeric value that represents the current position of the scroll box on the
scroll bar control.

public int Value { get; set; }

Long Answer Questions ( 4/5/6 Marks)

1. List and explain Visual Basic data types?


Ans
Data Type Size Range
Boolean It depends on the Platform. True or False

Byte 1 byte 0 to 255

Char 2 bytes 0 to 65535

Date 8 bytes 0:00:00am 1/1/01 to


II BCA C# and Dot Net Framework

11:59:59pm 12/31/9999

Decimal 16 bytes (+ or -)1.0 x 10e-28 to 7.9 x


10e28

Double 8 bytes 1.79769313486232e308 to


9,223,372,036,854,775,807

Integer 4 bytes -2,147,483,648 to


2,147,483,647

Long 8 bytes -9,223,372,036,854,775,808


to 9,223,372,036,854,775,807

Object 4 bytes on a 32-bit Any type can be stored in


platform, 8 bytes on a variable of type Object
a 64-bit platform

SByte 1 byte -128 to 127

Single 4 bytes -3.4028235E+38 through


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

String Depends on 0 to approximately 2 billion


platform Unicode characters

User- Depends on Each member of the structure


Defined Platform has a range determined by its
data type and is independent of
the ranges of the other members
II BCA C# and Dot Net Framework

2. Explain decision making with if..else if..else statement in VB.NET with syntax and
example
Ans:
Syntqx:
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If

If the Boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.

Example:
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
' check the boolean condition '
If (a = 10) Then
' if condition is true then print the following '
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
'if else if condition is true '
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
'if else if condition is true
Console.WriteLine("Value of a is 30")
Else
'if none of the conditions is true
Console.WriteLine("None of the values is matching")
End If
II BCA C# and Dot Net Framework

Console.WriteLine("Exact value of a is: {0}", a)


Console.ReadLine()
End Sub
End Module

An If statement can be followed by an optional Else if...Else statement, which is very useful
to test various conditions using single If...Else If statement.

When using If... Else If... Else statements, there are few points to keep in mind.

An If can have zero or one Else's and it must come after an Else If's.

An If can have zero to many Else If's and they must come before the Else.

Once an Else if succeeds, none of the remaining Else If's or Else's will be tested.

3. Explain Select case structure with syntax and example?


Ans
syntax:
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select

expression − is an expression that must evaluate to any of the elementary data type in
VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte,
Short, Single, String, UInteger, ULong, and UShort.

expressionlist − List of expression clauses representing match values for expression.


Multiple expression clauses are separated by commas.

statements − statements following Case that run if the select expression matches any
clause in expressionlist.
II BCA C# and Dot Net Framework

elsestatements − statements following Case Else that run if the select expression does not
match any clause in the expressionlist of any of the Case statements.

Example;:

Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module

4. Foreach..Next and Do..Until loops with their syntax and example


Ans: The syntax for this loop construct is −

Do { While | Until } condition


[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
II BCA C# and Dot Net Framework

Loop
-or-
Do
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition

Example:

Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a=a+1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module

The syntax for this loop construct is −

For Each element [ As datatype ] In group


[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]

Example:
II BCA C# and Dot Net Framework

Module loops
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
'displaying the values

For Each arrayItem In anArray


Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub

5. Write a note on scope of variables in VB.NET?


Ans:
The scope of an element is its accessibility in the code.
As we write larger programs, scope will become more important, because we'll be dividing
code into classes, modules, procedures, and so on. You can make the elements in those
programming constructs private, which means they are tightly restricted in scope. In VB
.NET, where you declare an element determines its scope.An element can have scope at
one of the following levels:

Block scope: A block is a series of statements terminated by an End, Else, Loop, or Next
statement, and an element declared within a block can be used only within that
block. It is available only within the code block in which it is declared.

Example:
A variable, strText is declared in an If statement. That variable can be used inside the If
statement's block, but not outside.
Module Module1
Sub Main()
Dim intValue As Integer = 1
If intValue = 1 Then
Dim strText As String = "No worries."
System.Console.WriteLine(strText)
End If
II BCA C# and Dot Net Framework

System.Console.WriteLine(strText) ' Will not work!


End Sub
End Module

Procedure scope— An element declared within a procedure is not available outside that
procedure, and only the procedure that contains the declaration can use it. Elements at
this level are also called local elements, and you declare them with the Dim or Static
statement.Module scope—available to all code within the module, class, or structure in
which it is declared .

Example:
Module Module1
Sub Main()
System.Console.WriteLine(Module2.Function1()) 'Will not work! End Sub
End Module
Module Module2
Private Function Function1() As String
Return "Hello from Visual Basic"
End Function
End Module

Namespace scope—available to all code in the namespace


Example: If you declare a variable in a module outside of any procedure, it has module
scope.
In the following program code, a Label control is declared and created that has module
scope:

Dim Label1 As Label


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As
System.EventArgs) Handles Button1.Click
Label1 = New Label
Label1.AutoSize = True
Label1.Location = New Point(15, 15)
:
:
:
II BCA C# and Dot Net Framework

End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As
System.EventArgs) Handles Button2.Click
Label1.AutoSize = False
Label1.Location = New Point(25, 25)
:
:
:
End Sub
When module-level variables are declared you can place the declaration outside any
procedure in the module. Declaring a variable in a procedure gives it procedure scope, and
so on.

6. Explain For loop with syntax and example


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

The syntax for this loop construct is −

For counter [ As datatype ] = start To end [ Step step ]


[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]

Example:

Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
II BCA C# and Dot Net Framework

Console.ReadLine()
End Sub
End Module

7. Write a note on Standard and Dynamic arrays?


Ans:
Standard Arrays
Dim statement is used to declare a standard array.
Examples of standard array declarations:
Dim Data(30)
-
The Data array now has 30 elements, starting from Data(0), which
is how you refer to the
first element, up to Data(29). 0 is the lower bound of this array, and 29 is the upper bound.

Dim Strings(10) As String

Dim TwoDArray(20, 40) As Integer


Dim Bounds(10, 100)
-
The Bounds array has two indices, one of which runs from 0 to 9, and the other of which
runs
from 0 to 99.

Dynamic Arrays :

A Dynamic array is used when we do not know how many items or elements to be inserted
in an array. To resolve this problem, we use the dynamic array. It allows us to
insert or store the number of elements at runtime in sequentially manner. A Dynamic
Array can be resized according to the program's requirements at run time using the
"ReDim" statement..

Syntax of ReDim:

ReDim [Preserve] varname(subscripts)


II BCA C# and Dot Net Framework

Preserve keyword is used to preserve the data in an existing array when you change the
size of the last dimension. The varname argument holds the name of the array to
(re)dimension. The subscripts term specifies the new dimension of the array.

Example for using dynamic arrays, in which we declare an array, dimension it, and then
redimension it:

Dim DynaStrings() As String


ReDim DynaStrings(10)
DynaStrings(0) = "String 0"

8. Explain the purpose of REDIM and PRESERVE keywords with suitable example
Ans: Dynamic Arrays:If you don't know the size of the array, dynamic arrays would be
very helpful for storing the data. The Redim and Preserve statements are used for this
purpose. For Dynamic array we should not provide the size when we declare the array.
After the declaration, we cannot change the data type and can specify size using redim
statement. Preserve keyword is used to preserve the data without losing when changing
the dimension of the array. Using Redim Preserve keyword, only last dimension can be
resized.

For Example : Dim Marks(10)


You can resize an array by using the ReDim statement. For example, to resize the
Marks array to hold 20 elements, you can use the following code:
ReDim Marks(20)

If you use the Preserve keyword while resizing an array, only the last dimension of the
array can be resizes.
Consider the following example,
Dim Marks (10,5) As Integer
Redim Preserve Marks(10,10) “Ok, The last dimension is resized.
Redim Preserve Marks(15,5) “Error, The first dimension is resized.

9. Write the syntax of creating Sub procedures in VB.NET. Give an example. ?


=Creating Procedures:
You declare Sub procedures with the Sub statement:

[{ Public | Protected | Friend | Protected Friend | Private }] Sub name [(arglist)]


[ statements ]
[ Exit Sub ]
[ statements ]
II BCA C# and Dot Net Framework

End Sub

Public-Procedures declared Public have public access. There are no restrictions on the
accessibility of public procedures.

Protected-:Procedures declared Protected have protected access. They are accessible only
from within their own class or from a derived class. Protected access can be specified only
on members of classes.

Private-Procedures declared Private have private access. They are accessible only within
their declaration context, including from any nested procedures. name-Name of
the Sub procedure.

arglist: List of expressions (which can be single variables or simple values) representing
arguments that are passed to the Sub procedure when it is called. Multiple arguments
are separated by commas.

statements:The block of statements to be executed within the Sub procedure. Each


argument in the arglist part has the following syntax and parts:

[{ ByVal | ByRef }] [ ParamArray ] argname [ As argtype ] [ = defaultvalue ] Here are the


parts of the arglist:

ByVal: Specifies passing by value. In this case, the procedure cannot replace or reassign
the underlying variable element in the calling code (unless the argument is a reference
type). ByVal is the default in Visual Basic.

ByRef: Specifies passing by reference. In this case, the procedure can modify the
underlying variable in the calling code the same way the calling code itself can.

ParamArray: Used as the last argument in arglist to indicate that the final argument is an
optional array of elements of the specified type. The ParamArray keyword allows you
to pass an arbitrary number of arguments to the procedure. A ParamArray argument is
always passed ByVal.

argname: Name of the variable representing the argument.


II BCA C# and Dot Net Framework

argtype: This part is optional unless Option Strict is set to On, and holds the data type of
the argument passed to the procedure. Can be Boolean, Byte, Char, Date, Decimal,
Double, Integer, Long, Object, Short, Single, or String; or the name of an enumeration,
structure, class, or interface.

defaultvalue :Required for Optional arguments. Any constant or constant expression that
evaluates to the data type of the argument.

Program.vb
Module Example
Sub Main()
Dim x As Integer = 55
Dim y As Integer = 32
Addition(x, y)
End Sub
Sub Addition(ByVal m As Integer, ByVal n As Integer)
Console.WriteLine(m+n)
End Sub
End Module

In the above example, we pass some values to the Addition procedure.

Addition(x, y)
Here we call the Addition procedure and pass two parameters to it. These parameters are
two Integer values.

Sub Addition(ByVal m As Integer, ByVal n As Integer)

Console.WriteLine(m+n)

End Sub

We define a procedure signature. A procedure signature is a way of describing the


parameters and parameter types with which a legal call to the function can be made. It
contains the name of the procedure, its parameters and their type, and in case of functions
II BCA C# and Dot Net Framework

also the return value. The ByVal keyword specifies how we pass the values to the
procedure. In our case, the procedure obtains two numerical values 55 and 32. These
numbers are added and the result is printed to the console.

Here, the keyword ByVal indicates that the numbers are passed by value, which means a
copy of the numbers are passed. This is the default in VB .NET. The other possibility is
ByRef, which means that the argument will be passed by reference.

10. Write the syntax of creating functions in VB.NET. Give example?


=Function statement is used to create a function:
Syntax is:

[{ Public | Protected | Friend | Protected Friend | Private }] Function name[(arglist)] [ As


type ]

[ statements ]
[ Exit Function ]
[ statements ]

End Function

Where
Public: Functions declared Public have public access. There are no restrictions on the
accessibility of functions.

Protected-:Functions declared Protected have protected access. They are accessible only
from within their own class or from a derived class. Protected access can be specified only
on members of classes.

Friend-: Functions declared Friend have friend access. They are accessible from within
the program that contains their declaration and from anywhere else in the same assembly.

Protected Friend- Functions declared Protected Friend have both protected and friend
accessibility. They can be used by code in the same assembly, as well as by code in derived
classes.
II BCA C# and Dot Net Framework

Private- Functions declared Private have private access. They are accessible only within
their declaration context, including from any nested functions.

name-Name of the function.

arglist-List of expressions (which can be single variables or simple values)


representingarguments that are passed to the function when it is called. Multiple
arguments are
separated by commas.

statements-The block of statements to be executed within the function.

As type - which specifies the type of the return value from the function;

When you use ByVal (the default in VB .NET), you pass a copy of a variable to a procedure;
when you use ByRef, you pass a reference to the variable, and if you make changes to that
reference, the original variable is changed.

The Return statement simultaneously assigns the return value and exits the function.
Any number of Return statements can appear anywhere in the function.

ex:

Module Example
Dim x As Integer = 55
Dim y As Integer = 32

Dim result As Integer


Sub Main()

result = Addition(x, y)
Console.WriteLine(Addition(x, y))

End Sub
II BCA C# and Dot Net Framework

Function Addition(ByVal m As Integer, ByVal n As Integer) As Integer


Return m+n
End Function
End Module

11. Explain any four methods of windows form control?


=Method : Description
Activate - Activates the form (gives it focus and makes it
activite).

Close - Closes the form

Hide - Hides the form

Focus - Gives the form the focus

12. Explain any FIVE unique properties of Form?


= Property : Description
Focused - Indicates if the form has input focus.
Height - Gets or sets the height of the form.
IsMdiChild - Indicates if the form is an MDI child form .
Text - Gets or sets the text associated with this form.
Visible - Gets or sets a value indicaƟ ng if the form isvisible.

13. Explain MsgBox Function with an example.


Syntax

Msgbox (“Message”, [buttons], [title])

= Message - A string expression displayed as the message in the dialog box. The maximum
length is about 1,024 characters.

Button type - type of buttons to display, the icon style to use. This is optional. Default is
0.The
following table shows some of the constants used for type of buttons
II BCA C# and Dot Net Framework

title - String expression displayed in the title bar of the dialog box. This is also optional. If
title is not given, the application name is placed in the title bar .
MsgBox Function returns a value indicating which button the user has chosen.

The MsgBox function can return one of the following values which can be used to identify
the button the user has clicked in the message box.

1 - vbOK - OK was clicked


· 2 - vbCancel - Cancel was clicked
· 3 - vbAbort - Abort was clicked
· 4 - vbRetry - Retry was clicked
· 5 - vbIgnore - Ignore was clicked
· 6 - vbYes - Yes was clicked
· 7 - vbNo - No
Example:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox("Hi Friend, This is a message box!", MsgBoxStyle.OkCancel, "Message Box")
End Sub

14. Explain InputBox Function with an example?


Ans: The InputBox function prompts the users to enter values. After entering the values, if the
user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return
the text in the text box.

Syntax

InputBox(prompt[,title][,default])

Parameter Description

Prompt − A required parameter. A String that is displayed as a message in the dialog box. The
maximum length of prompt is approximately 1024 characters. If the message extends to more
than a line, then the lines can be separated using a carriage return character (Chr(13)) or a
linefeed character (Chr(10)) between each line.

Title − An optional parameter. A String expression displayed in the title bar of the dialog box. If
the title is left blank, the application name is placed in the title bar.
II BCA C# and Dot Net Framework

Default − An optional parameter. A default text in the text box that the user would like to be
displayed.

Example

Let us calculate the area of a rectangle by getting values from the user at run time with the help
of two input boxes (one for length and one for width).

Function findArea()

Dim Length As Double

Dim Width As Double

Length = InputBox("Enter Length ", "Enter a Number")

Width = InputBox("Enter Width", "Enter a Number")

findArea = Length * Width

End Function

15. Explain Handling Mouse Events?


=Mouse events can be handled in forms and controls. The following are the possible events
for the Control class, which is a base class for controls and forms:
MouseDown— Happens when the mouse pointer is over the control and a mouse buƩ on
is
pressed.
MouseEnter— Happens when the mouse pointer enters the control.
MouseHover— Happens when the mouse pointer hovers over the control.
MouseLeave— Happens when the mouse pointer leaves the control.
MouseMove— Happens when the mouse pointer is moved over the control.
MouseUp— Happens when the mouse pointer is over the control and a mouse buƩ on is
released. MouseWheel— Happens when the mouse wheel moves while the control has
focus.
Example 1:
Private Sub Form1_MouseDown(ByVal sender As Object, _ ByVal e As
System.Windows.Forms.MouseEventArgs) _ Handles MyBase.MouseDown
If e.Butt on = MouseButtons.LeŌ Then
TextBox1.Text = "Mouse down at " + CStr(e.X) + ", " + CStr(e.Y)
End If
End Sub
II BCA C# and Dot Net Framework

The above code displays the x and y axis value of the mouse in TextBox1 whenever the
mouse is pressed down.

16. Explain the following properties of a textbox


i) Multiline
ii) MaxLength
iii) Wordwrap
iv) Scrollbar
v) PasswordChar
Ans:
Multiline:Gets or sets a value indicating whether this is a multiline TextBox control.
MaxLength You can specify the maximum number of characters that can be entered into
the TextBoxExt control by using MaxLength property. The default value is 32767 .

WordWrap: Indicates whether a multiline text box control automatically wraps words to
the beginning of the next line when necessary.
PasswordChar: Gets or sets the character used to mask characters of a password in asingle-
line TextBox control.
ReadOnly: Gets or sets a value indicating whether text in the text box is read-only.
ScrollBars: Gets or sets which scroll bars should appear in a multiline TextBox control.
This property has values.

• None
• Horizontal
• Vertical
• Both

TextLength: Gets the length of text in the control.

17. Explain the procedure for creating the text box in code with example code.

We can create our own textbox using the TextBox class.

Step 1 : Create a textbox using the TextBox() constructor provided by the TextBox class.
// Creating textbox
TextBox Mytextbox = new TextBox();

Step 2 : After creating TextBox, set the properties of the TextBox provided by the
TextBox class.

// Set location of the textbox


Mytextbox.Location = new Point(187, 51);

// Set the name of the textbox


II BCA C# and Dot Net Framework

Mytextbox.Name = "text_box1";
Step 3 : And last add this textbox control to from using Add() method.
// Add this textbox to form
this.Controls.Add(Mytextbox);

Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace my {

public partial class Form1 : Form {

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{

// Creating and setting the properties of TextBox1


TextBox Mytextbox = new TextBox();
Mytextbox.Location = new Point(187, 51);
Mytextbox.BackColor = Color.LightGray;
Mytextbox.ForeColor = Color.DarkOliveGreen;
Mytextbox.AutoSize = true;
Mytextbox.Name = "text_box1";

// Add this textbox to form


this.Controls.Add(Mytextbox);
text_box1.Text= “HARISH KANCHAN”;
}
}
}
II BCA C# and Dot Net Framework

18. Write the code for following with reference to ListBox:


i. Adding items
ii. Sorting items
iii. Determining number of many items
iv. Determining items selected.
v. Removing items

Adding Items to ListBox


Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
' Set the caption bar text of the form.
Me.Text = "Kanchan"
ListBox1.Items.Add("BCA")
ListBox1.Items.Add("BBA")
ListBox1.Items.Add("BCom")
ListBox1.Items.Add("BSc")
ListBox1.Items.Add("BSW")
ListBox1.Items.Add("BA")
End Sub

Sorting Items
Private Sub BtnSort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnSort.Click
ListBox1.Sorted = True
End Sub
II BCA C# and Dot Net Framework

Counting ListBox Items


Private Sub BtnCount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnCount.Click
Label1.Text = ListBox1.Items.Count
End Sub

Finding Selected Item of ListBox


Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnFind.Click
Label2.Text = ListBox1.SelectedItem.ToString()
End Sub

Removing Items From ListBox


Private Sub BtnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnRemove.Click
ListBox1.Items.Clear()
End Sub
II BCA C# and Dot Net Framework

'removing the selected item


Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
ListBox1.Items.Remove(ListBox1.SelectedItem.ToString)
End Sub

19. Write procedure to set the following for the button’s click event :
i. Button’s caption
ii. Button’s foreground and background color
iii. Button’s font
Ans:
i).Button’s caption

By writing following code also we set caption to a button.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


' Set the caption bar text of the Button.
Button1.Text = "Submit"

End Sub
Or else Text property is used to Get or set the Caption to Button control.

ii) Button’s foreground and background color


private void button1_Click(object sender, EventArgs e) {

Button button = sender as Button;


button.ForeColor = Color.FromName(txtForeground.Text);
button.BackColor = Color.FromName(txtBackground.Text);
}

iii) Button’s Font

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handl


es Button1.Click
Dim myFont As System.Drawing.Font
myFont = New System.Drawing.Font("Arial", 12,FontStyle.Bold Or FontStyle.Italic)
Me.Font = myFont
Button1.Text = "My font was changed to this"
End Sub

20. What is the use of trackbar? Explain its unique properties.

The Windows Forms TrackBar control (also sometimes called a "slider" control) is used
for navigating through a large amount of information or for visually adjusting a numeric
setting. The TrackBar control has two parts: the thumb, also known as a slider, and the tick
marks. The thumb is the part that can be adjusted.

Trackbar
II BCA C# and Dot Net Framework

Properties of Trackbar Control

PROPERTY DESCRIPTION

Specify the lower end and upper end of the range which thumbs
Minimum and Maximum can scroll over. It is possible to specify a negative value for the
Minimum.

Gets or sets the value of the thumb in SingleThumb mode of


Value
RadTrackBar

Controls whether the tick marks are drawn on one or both sides
of the control. The default value is Both.
Setting TickStyle to None will disable the ticks.
Setting TickStyle to Both will enable ticks on both sides.
Setting TickStyle to TopLeft will show only the ticks on the top
TickStyle
side, when the Orientation is Horizontal. If the Orientation is set
to Vertical, only the ticks on the left side will be shown.
Setting TickStyle to BottomRight will show only the ticks on the
down side, when the Orientation is Horizontal. If the Orientation
is set to Vertical, only the ticks on the right side will be shown.

Orientation Gets or Sets the orientation of the RadTrackBar.

Gets or sets the change in value that one click of the mouse
LargeChange
outside of the slider makes.
II BCA C# and Dot Net Framework

PROPERTY DESCRIPTION

Gets or Sets the number of positions that the trackbar moves in


SmallChange
response to keyboard arrow keys and the trackbar buttons.

Gets or Sets the orientation of the text associated with TrackBar.


TextOrientation
Whether it should appear horizontal or vertical.

Controls the visibility of the navigation buttons in RadTrackBar.


ShowButtons By default these buttons are not displayed. To show them, set the
property to true.

Sets the spacing between the large tick marks. The default value
LargeTickFrequency
is 5.

Sets the spacing between the small tick marks. The default value
SmallTickFrequency
is 1.

Determinates in which mode the control will operate.


TrackBarMode
Each mode has different functionality and behavior.

Ranges Gets the TrackBarRangeCollection.

ThumbSize Gets or Sets TrackBar's Size.

Controls whether the line down the middle of the control where
ShowSlideArea
the slider rides is drawn. The default value is true.
II BCA C# and Dot Net Framework

21. What is use of Progress bar control ? Explain its unique properties
Ans: It represents a Windows progress bar control. It is used to provide visual
feedback to your users about the status of some task. It shows a bar that fills in from
left to right as the operation progresses.

Property & Description

BackgroundImage
Gets or sets the background image for the ProgressBar control.

BackgroundImageLayout
Gets or sets the layout of the background image of the progress bar.

CausesValidation
Gets or sets a value indicating whether the control, when it receives
focus, causes validation to be performed on any controls that require
validation.

Font
Gets or sets the font of text in the ProgressBar.

MarqueeAnimationSpeed
Gets or sets the time period, in milliseconds, that it takes the progress
block to scroll across the progress bar.

Maximum
Gets or sets the maximum value of the range of the control.v

Minimum
Gets or sets the minimum value of the range of the control.

Padding
Gets or sets the space between the edges of a ProgressBar control
and its contents.

RightToLeftLayout
Gets or sets a value indicating whether the ProgressBar and any text
it contains is displayed from right to left.

Step
II BCA C# and Dot Net Framework

Gets or sets the amount by which a call to the PerformStep method


increases the current position of the progress bar.

Style
Gets or sets the manner in which progress should be indicated on the
progress bar.

Value
Gets or sets the current position of the progress bar.v

22. How do you add and remove items to / from a ComboBox? Explain with example

Items can be added to a Windows Forms combo box, list box in a variety of ways, because these controls
can be bound to a variety of data sources. The text that is displayed in the control is the value returned by
the object's ToString method.

To add items

1. Add the string or object to the list by using the Add method of the ObjectCollection class. The
collection is referenced using the Items property:

comboBox1.Items.Add("BCA");
comboBox1.Items.Add("BCOM");

• or -
2. Insert the string or object at the desired point in the list with the Insert method:

ComboBox1.Items.Insert(0, "BBA");
ComboBox1.Items.Insert(1, "BSC");
ComboBox1.Items.Insert(2, "BSW");
ComboBox1.Items.Insert(3, "BA");

• or -
3. Assign an entire array to the Items collection:

System.Object[] ItemObject = new System.Object[10];


for (int i = 0; i <= 9; i++)
{
ItemObject[i] = "Item" + i;
}
listBox1.Items.AddRange(ItemObject);

To remove an item

Call the Remove or RemoveAt method to delete items.

Remove has one argument that specifies the item to remove.RemoveAt removes the item with
the specified index number.
II BCA C# and Dot Net Framework

// To remove item with index 0:


comboBox1.Items.RemoveAt(0);
// To remove currently selected item:
comboBox1.Items.Remove(comboBox1.SelectedItem);
// To remove "Tokyo" item:
comboBox1.Items.Remove("BBA");

To remove all items

Call the Clear method to remove all items from the collection:

ComboBox1.Items.Clear();

23. Explain the following with reference to PictureBox:


i. Setting or Getting the Image
ii. Adjusting size to contents
iii. Handling events
Ans:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

// i.Setting or Getting the Image


pictureBox1.Image = Image.FromFile+ @"D:\\Kanchan\Sona.Jpg");

// ii.Adjusting size to contents


PictureBox1.ClientSize = New Size(300, 300)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Sub

iii.Handling events
The following given below are some commonly used Events of the PictureBox
Control in VB.net.

PictureBox Control in VB.net


# Description
Events

1. CausesValidationChanged Overrides the Control.CausesValidationChanged property.

2. Click Occurs when the control is clicked.

3. Enter Overrides the Control.Enter property.

4. FontChanged Occurs when the value of the Font property changes.

5. ForeColorChanged Occurs when the value of the ForeColor property changes.


Harish Kanchan II BCA C# and Dot Net Framework

6. KeyDown Occurs when a key is pressed when the control has focus.

7. KeyPress Occurs when a key is pressed when the control has focus.

8. KeyUp Occurs when a key is released when the control has focus.

9. Leave Occurs when input focus leaves the PictureBox.

Occurs when the asynchronous image-load operation is completed,


10. LoadCompleted
been canceled, or raised an exception.

Occurs when the progress of an asynchronous image-loading


11. LoadProgressChanged
operation has changed.

12. Resize Occurs when the control is resized.

13. RightToLeftChanged Occurs when the value of the RightToLeft property changes.

14. SizeChanged Occurs when the Size property value changes.

15. SizeModeChanged Occurs when SizeMode changes.

16. TabIndexChanged Occurs when the value of the TabIndex property changes.

17. TabStopChanged Occurs when the value of the TabStop property changes.

18. TextChanged Occurs when the value of the Text property changes.
II BCA C# and Dot Net Framework

Unit-4
TWO MARKS QUESTION

1. What is ADO.NET ?
ADO.NET is a data access technology from the Microsoft .NET Framework that
provides communication between relational and non-relational systems through a
common set of components. Data-sharing consumer applications can use ADO.NET
to connect to these data sources and retrieve, handle, and update the data that they
contain.

2. What is databinding ? Mention types of databinding.

Data Binding is binding controls to data from databases. With data binding we
can bind a control to a particular column in a table from the database or we can bind
the whole table to the data grid. Data binding provides simple, convenient, and
powerful way to create a read/write link between the controls on a form and the data
in their application.

Data binding can be:

• Simple Data binding

• Complex Data binding

3. Differentiate simple and complex binding .

Simple databinding is supported by controls like TextBoxes. In Simple databinding, only


one data value can be displayed by the control at a time.
In complex databinding, which is supported by controls like the DataGrid, more than one
data value from the DataSource can be displayed.
4. What is Data Bound control ? Give example

These controls are used to bind with the data source controls to display and modify
data in Web application easily. Web server controls that support complex binding are:

• Grid View Control

• Data List Control

• Form View Control

• Details View Control


II BCA C# and Dot Net Framework

• List View Control

• DataPager Control

• Repeater Control

• Chart Control

5. List any four ADO.NET objects.


• Dataset
• DataAdapter
• DataConnectionObject
• Command Object

6. What is use of Data Reader object?

Data views—Data views represent a customized view of a single table that can be
filtered, searched, or sorted. In other words, a data view, supported by the DataView
class, is a data "snapshot" that takes up few resources

Constraint objects—Datasets support constraints to check data integrity. A constraint,


supported by the Constraint class, is a rule that can be used when rows are inserted,
updated, or deleted to check the affected table after the operation. There are two types
of constraints: unique constraints check that the new values in a column are unique
throughout the table, and foreign-key constraints specify how related records should
be updated when a record in another table is updated.

DataRelation objects—DataRelation objects specify a relationship between parent and


child tables, based on a key that both tables share. DataRow objects—DataRow objects
correspond to a particular row in a data table. You use the Item property to get or set
a value in a particular field in the row.

DataColumn objects—DataColumn objects correspond to the columns in a table. Each


object has a DataType property that specifies the kind of data each column contains,
such as integers or string values.

7. Differentiate execute Non Query and Execute Scalar

Executes a non-row returning SQL statement, it will return number of rows effected
with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method will be
used only for insert, update and delete, Create, and SET statements.
II BCA C# and Dot Net Framework

Executes the command and returns the value in the first column in the first row of the
result. i.e. single value, on execution of SQL Query using command object. It’s very fast
to retrieve single values from database.

What is dataset ?

Dataset— Dataset is the local copy of your database which exists in the local system
and makes the application execute faster and reliable. Datasets store data in a
disconnected cache. The structure of a dataset is similar to that of a relational
database. It gives access to an object model of tables, rows, and columns, and it
contains constraints and relationships defined for the dataset.

8. How to create Dataset and populate it with data ?

Creating and populating Dataset in code An instance of a DataSet can be created by


calling the DataSet constructor as follows:

ds=New DataSet()

A DataSet can include data local to the application, and data from multiple data
sources. Interaction with existing data sources is controlled through the DataAdapter.

The SelectCommand property of the DataAdapter is a Command object that retrieves


data from the data source. Using the Fill() method of the DataAdapter data set can be
populated.

9. What is Web server control ?

Web server controls include traditional form controls such as buttons and text boxes
as well as complex controls such as tables. They also include controls that provide
commonly used form functionality such as displaying data in a grid, choosing dates,
displaying menus etc.

10. List any four public properties of Button web server control
II BCA C# and Dot Net Framework

11. What is use of postbackUrl and causesValidation Property of web control. ?

12. What is use of Textmode property of Textbox web control

Event : TextChanged – Occurs when user changes the text of a TextBox control

Button

Button control is used to perform events. It is also used to submit client request to the
server. Syn ASP.NET provides three types of button control:

• Button : It displays text within a rectangular area.

• Link Button : It displays text that looks like a hyperlink.

• Image Button : It displays an image on the rectangular area of the button.

13. What is Validation Control ? List any two.

These are the controls used for validating the data entered in an input control. These
controls belong to the BaseValidator class.

The different validation controls are:

• RequiredFieldValidator

• RangeValidator

• RegularExpressionvalidator

• CompareValidator

• CustomValidator

• ValidationSummaryControls

14. Give the default syntax of asp.net source code added for Textbox web
control when it is placed in designer window .
II BCA C# and Dot Net Framework

15. What is use of Databind and Updaterow methods of Gridview web control.

DataBind – Binds the data from the data source with the GridView control

UpdateRow – Updates the row specified by index using the field values of that row.

16. What is use of Autogeneraterows Properties of detailedview Control.

AutoGenerateRows - Gets or sets a value indicating whether row fields for each field in
the data source are automatically generated and displayed in a DetailsView control.

The DetailsView Control is a data bound control. It is used to display a single record
from the associated datasource in a table format. It also supports insert,update,delete
operations.

17. What is formview control ? List any two properties.

The FormView Control displays only a single record in a table at a time retrieved from
a datasource.

The FormView Control resides within System.Web.UI.WebControls namespace.

18. What is use of repeater web control ?

The Repeater Control is a data bound control that is used to display repeated list of
items from the associated datasource. A Repeater is used when you want to display
data repeatedly, but not necessarily in a tabular format. It enables you to create custom
lists out of any data that is available to the page. Performance wise Repeater is the
fastest data bound control in ASP.Net.

19. What is use of Data Pager Control ?

The DataPager control is used to provide paging functionality to the data-bound


controls such as ListView control. The DataPager control can be associated with the
data-bound control by using the PagedControlID property.

Font,ForeColor,GroupTemplate, PagedControlID – properties

DeleteItem,ExtractItemvalue,Sort – methods
II BCA C# and Dot Net Framework

3/4/5 marks Question and Answer

1. Explain any two ADO.NET Objects.

Data connection objects— The ADO Connection Object is used to create an open
connection to a data source. Through this connection, you can access and manipulate
a database.If you want to access a database multiple times, you should establish a
connection using the Connection object. It uses OracleConnection or OleDbConnection
or SqlConnection objects to communicate with a data source. Details used to create a
connection to a data source can be set using the ConnectionString property of the
connection object. Connection to the database can be opened by calling the Open()
method and connection is closed by Close() method.

Data adapters— The DataAdapter works as a bridge between a DataSet and a data
source to retrieve data. DataAdapter is a class that represents a set of SQL commands
and a database connection. It can be used to fill the DataSet and update the data
source. Data adapters are a very important part of ADO.NET. Data adapters are used
to communicate between a data source and a dataset. Data adapter populates the data
set using Fill() method. The different types of data adapters are:

• OleDbDataAdapter

• OdbcDataAdapter

• OracleDataAdapter

• SqlDataAdapter

Command objects— The ADO Command object is used to execute a single query
against a database. The query can perform actions like creating, adding, retrieving,
deleting or updating records. Data adapters support four properties that give you
access to these command objects: SelectCommand, InsertCommand,
UpdateCommand, and DeleteCommand. The CommandText property of command
object sets a provider command. The CommandType property sets the type of the
command object.

Dataset— Dataset is the local copy of your database which exists in the local system
and makes the application execute faster and reliable. Datasets store data in a
disconnected cache. The structure of a dataset is similar to that of a relational
database. It gives access to an object model of tables, rows, and columns, and it
contains constraints and relationships defined for the dataset
II BCA C# and Dot Net Framework

2. Explain Simple binding with example

Simple Data binding: Simple databinding is supported by controls like TextBoxes. In


Simple databinding, only one data value can be displayed by the control at a time.

Example: To bind a text box's Text property to the customer_name field in the
customers table from the database in a dataset, DataSet1, select the text box and
expand its (DataBindings) property in the Properties window. You can select a field in
a dataset to bind to just by clicking a property and selecting a table from the drop-
down list that appears.

Simple binding can be done in code, using a control's DataBindings property as


follows:

TextBox1.DataBindings.Add("Text", DataSet1, "customers.customer_name")

3. Explain complex data binding with example.

Complex Data binding: Complex data binding allows a control to bind more than one
data element , such as more than one record in a database, at the same time.

Complex data binding uses 3 properties:

DataSource – typically a data set

DataMember- typically a table in a data set

DisplayMember- the field you want a control to display

ValueMember- the field you want a control to return in properties like selected value

Example: The following code binds a table ‘student’ to a Gridview control


DataGridView1.

DIM con AS NEW SQLCONNECTION

DIM ds AS DATASET

DIM cmd AS NEW SQLCOMMAND

DIM adp AS DATA ADAPTER

DIM cmdstr AS STRING


II BCA C# and Dot Net Framework

Cmdstr = “select * from student”

Cmd= NEW SQLCOMMAND(cmdstr,con)

Adp= NEW SQLDATAADAPTER(cmd)

ds = NEW DATASET()

Adp.Fill(ds,”student”)

DATAGRIDVIEW1.DATAMEMBER = “student”

DATAGRIDVIEW1.DATASOURCE = ds

4. Write a note on Navigating in Datasets

Navigating in Datasets Navigation controls let the user to move from record to record.
The BindingContext property sets the location in various data sources that are bound in
the form.

Displaying the Current Location – Current position can be obtained by using the form's
Binding Context property's Position member, as follows:

Me.BindingContext(Dataset1,”table1”).Position

Moving to the Next Record – Navigation to the next record can be done by
incrementing the Position property of the binding context.
Me.BindingContext(Dataset1,”table1”).Position=Me.BindingContext(Dataset1,”table1”).Po
sition+1

Moving to the Previous Record - Navigation to the previous record can be done by
decrementing the Position property of the binding context.
Me.BindingContext(Dataset1,”table1”).Position=Me.BindingContext(Dataset1,”table1”).Po
sition-1

Moving to the First Record - Moving to the first record in the binding context can be
done by setting the Position property to 0.
Me.BindingContext(Dataset1,”table1”).Position=0

Moving to the Last Record – The Count property returns the total number of records in
the table. Since the index of the records start from 0 Count-1 will be the last record.

Navigation to the last record can be done as follows:


Me.BindingContext(Dataset1,”table1”).Position=Me.BindingContext(Dataset1,”table1”).count-1
II BCA C# and Dot Net Framework

5. Explain SqlConnection Class

6. Explain SqlCommand Class


II BCA C# and Dot Net Framework

7. Explain SqlDataAdapter Class

8. Explain DataSet Class


II BCA C# and Dot Net Framework

9. Explain SqlDataReader Class

10. Explain web button control with any five public properties

11. Explain following validation controls


i. The RequiredFieldValidator controls
ii. The RangeValidator control
iii. The RegularExpressionValidator control
iv. The CompareValidator control
II BCA C# and Dot Net Framework

v. The CustomValidator control


vi. The ValidationSummary control

Ans: The RequiredFieldValidator Control:

The RequiredFieldValidator control ensures that the user has entered the required data in
the input control, such as text box control to which it is bound. With this control, the
validation fails if the input value does not change from its initial value. By default, the
initial value is an empty string ("").The InitialValue property does not set the default value
for the input control. It indicates the value that you do not want the user to enter in the
input control.

Property Description
InitialValue Specifies the starting value of the input control. Default value is ""
Output:

The RangeValidator Control

The RangeValidator Control checks whether or not the value of an input control lies within
a specified range of values. This control is used to check that the user enters an input
value that falls between two values. It is possible to check ranges within numbers, dates,
and characters. The validation will not fail if the input control is empty.
Use the RequiredFieldValidator control to make the field required. The following are the
properties of RangeValidator control:

• ControlToValidate – Contains the input control to validate

• Minimum Value – Holds the minimum value of the valid range


II BCA C# and Dot Net Framework

• Maximum Value – Holds the maximum value of the valid range

Property Description

MaximumValue Specifies the maximum value of the input control


MinimumValue Specifies the minimum value of the input control

Output:

The RegularExpressionValidator Control

The RegularExpressionValidator control is used to ensure that an input value matches a


specified pattern. It checks whether the text in the input control matches the format
specified by the regular expressions like email-id, date format. This control exists within
the Sysem.Web.UI.WebControls namespace

Property Description
ValidationExpressi Specifies the expression used to validate input control. The
on expression
II BCA C# and Dot Net Framework

Output:

The CompareValidator Control

The CompareValidator control is used to compare the value entered by a user into one
input control with the value entered into another or with an already existing value. This
control exists within the Sysem.Web.UI.WebControls namespace

Property Description
ControlToCompare Obtains or sets the input control to compare with the input
control
Operator Sets the comparison operator like equal, notequal,greaterthan,

ValueToCompare Sets a constant value to compare with the value entered by the
user

Output:
II BCA C# and Dot Net Framework

The CustomValidator Control

The CustomValidator control allows you to write a method to handle the validation of the
value entered. It checks the input given matches with a given condition or not. It basically
validates the input provided by the user against user-defined validations. This control
exists within the Sysem.Web.UI.WebControls namespace

Property Description

ClientValidationFunction Specifies the name of the client-side validation script


function to be executed.

ValidateEmptyText Sets a Boolean value indicating whether empty text should be


validated or not

Output:

The ValidationSummary Control

The ValidationSummary control is used to display a summary of all validation errors


occurred in a Web page at one place. The error message displayed in this control is
specified by the ErrorMessage property of each validation control. If the ErrorMessage
property of the validation control is not set, no error message is displayed for that
validation control.This control exists within the Sysem.Web.UI.WebControls namespace.

Property Description
DisplayMode How to display the summary. Legal values are:

• BulletList
II BCA C# and Dot Net Framework

EnableClientScript A Boolean value that specifies whether client-side validation is

ForeColor The fore color of the control


HeaderText A header in the ValidationSummary control
ShowMessageBox A Boolean value that specifies whether the summary should be

ShowSummary A Boolean value that specifies whether the ValidationSummary

Output:

12. Explain any five properties of GrideView web control

The important properties of GridView control are:

AllowPaging – Obtains or sets a value indicating whether the paging feature is enabled
AllowSorting - Obtains or sets a value indicating whether the sorting feature is enabled

Columns - Obtains a collection of DataControlObjects that represents the data


columns in a GridView control.

Rows – Obtains a collection of GridViewRow objects that represents the data rows in
a GridView control.

SelectedIndex – Obtains or sets the index of the selected row in GridView


II BCA C# and Dot Net Framework

SelectedRow - Obtains a reference to GridViewRow object of the selected row in


GridView

13. Explain any four methods of GrideView web control

The important methods of GridView control are:

DataBind – Binds the data from the data source with the GridView control

DeleteRow – Deletes the record present at the specified location from the data source

Sort – Sorts the GridView control according to the sort expression and direction
specified UpdateRow – Updates the row specified by index using the field values of that
row.

14. Explain any five properties of DetailedView web control

Some important properties of DetailsView Control:

Allowpaging - Gets or sets a value indicating whether the paging feature is enabled.

DataSource - Gets or sets the object from which the data-bound control retrieves its
list of data items.

Font - Gets the font properties associated with the Web server control

BackImageUrl - Gets or sets the URL to an image to display in the background of a


DetailsView control.

AutoGenerateRows - Gets or sets a value indicating whether row fields for each field in
the data source are automatically generated and displayed in a DetailsView control.

15. Explain any four methods of DetailedView web control

Important methods of DetailsView Control:

DeleteItem - Deletes the current record from the data source.

UpdateItem - Updates the current record from the data source.

InserItem - Inserts the current record in the data source.

DataBind - Calls the DataBind() method of the base class.

CreateTable - Creates the containing table for the DetailsView control.

You might also like