C# Dot Net Solved QB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

Harish Kanchan II BCA C# and Dot Net Framework

UNIT -1
Two Mark Questions
1. What are web browser and web server?

Web Browser: The web browser is an application software to explore www (World Wide
Web). It provides an interface between the server and the client and requests to the server
for web documents and services.

Web Server: Web server is a program which processes the network requests of the users
and serves them with files that create web pages. This exchange takes place using
Hypertext Transfer Protocol (HTTP).

2. What is web pages?

Web Pages: A webpage is a hypertext digital document that is linked to the World Wide
Web and viewable by anyone connected to the internet has a web browser.

3. What are the Frontend Languages?

The front end is the part of the website users can see and interact with such as the
graphical user interface (GUI) and the command line including the design, navigating
menus, texts, images, videos, etc.
Languages used for the front end are HTML, CSS, JavaScript, AJAX etc.

4. What are the Backend Languages?

The backend is the part of the website users cannot see and interact with. The backend
is the server side of the website. It stores and arranges data, and also makes sure
everything on the client side of the website works fine. Languages used for the back end
include Java, Ruby, PHP, Python, C# etc.

5. What is HTML?

• HTML stands for Hyper Text Markup Language


• HTML is the standard markup language for creating Web pages
• HTML describes the structure of a Web page
• HTML consists of a series of elements
• HTML elements tell the browser how to display the content
• HTML elements label pieces of content such as "this is a heading", "this is a paragraph",
"this is a link", etc.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 1
Harish Kanchan II BCA C# and Dot Net Framework

6. What is an HTML Element?

An HTML element is defined by a start tag, some content, and an end tag:<tagname>
Content goes here... </tagname>
The HTML element is everything from the start tag to the end tag:
<h1>My First Heading</h1>
<p>My first paragraph.</p>
Some HTML elements have no content (like the <br> element). These elements are called
empty elements. Empty elements do not have an end tag.

7. List the two types of tags in HTML

There are two types of tags in HTML that are:


1. Paired Tags (Opening and Closing Tags) 2. Unpaired Tags (Singular Tag)
Paired Tags:
A tag is said to be a paired tag if the text is placed between a tag and its companion tag. In
paired tags, the first tag is referred to as Opening Tag and the second tag is referred to as
Closing Tag.
Example: <i>This text is in italics. </i>
Unpaired Tags:
An unpaired tag does not have a companion tag or closing tag. Unpaired tags are also known
as Singular or Stand-Alone Tags. Example:<br> , <hr>

8. Write a note on HTML Heading tags.

• A HTML heading or HTML h tag can be defined as a title or a subtitle which you want
to display on the webpage. When you place the text within the heading tags
<h1>.........</h1>, it is displayed on the browser in the bold format and size of the text
depends on the number of heading.
• There are six different HTML headings which are defined with the <h1> to <h6> tags,
from highest level h1 (main heading) to the least level h6 (least important heading).
• h1 is the largest heading tag and h6 is the smallest one. So h1 is used for most
important heading and h6 is used for least important.
• Headings in HTML helps the search engine to understand and index the structure of
web page.
The following code shows all the heading levels, in use.
<h1>Heading level 1</h1>
<h2>Heading level 2</h2>

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 2
Harish Kanchan II BCA C# and Dot Net Framework

<h3>Heading level 3</h3>


<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>

9. Write a note on HTML DIV tag.

The div tag is known as Division tag. The div tag is used in HTML to make divisions of
content in the web page like (text, images, header, footer, navigation bar, etc). Div tag has
both open(<div>) and closing (</div>) tag and it is mandatory to close the tag. The Div is
the most usable tag in web development because it helps us to separate out data in the
web page and we can create a particular section for particular data or function in the web
pages.
• Div tag is Block level tag
• It is a generic container tag
• It is used to the group of various tags of HTML so that sections can be created and style
can be applied to them.

10. What are HTML Table – Rowspan and – Colspan

HTML Table – Rowspan: To make a cell span over multiple rows, use the rowspan
attribute: The value of the rowspan attribute represents the number of rows to span.
Ex:
<table>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
</table>
HTML Table – Colspan: To make a cell span over multiple columns, use the colspan
attribute. The value of the colspan attribute represents the number of columns to span.
Example:
<table>
<tr> <th colspan="2">Name</th>
<th>Age</th>
</tr>
</table>

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 3
Harish Kanchan II BCA C# and Dot Net Framework

11. Write a note on HTML <a> Tag.

The <a> tag defines a hyperlink, which is used to link from one page to another. The
most important attribute of the <a> element is the href attribute, which indicates the link's
destination.
Example: <a href="https://www.google.co.in">Visit Google<a>
Attributes
Attribute Value Description
download filename Specifies that the target will be downloaded when a user
clicks on
the hyperlink
href URL Specifies the URL of the page the link goes to
target _blank Specifies where to open the linked document
_parent
_self
_top
type media_type Specifies the media type of the linked document
By default, links will appear as follows in all browsers:
• An unvisited link is underlined and blue
• A visited link is underlined and purple
• An active link is underlined and red

12. Write a note on HTML <img> Tag.

HTML <img> tag is used to add image inside webpage/website. Nowadays website does
not directly add images to a web page, as the images are linked to web pages by using
the <img> tag which holds space for the image.
Syntax:
<img src="" alt="" width="" height="">
Ex: <img src="tiger.jpg" alt="Tiger Face" width="200" height="300">
Attributes: The <img> tag has following attributes.
• src: It is used to specify the path to the image.
• alt: It is used to specify an alternate text for the image. It is useful as it informs the
user about what the image means and also due to any network issue if the image cannot
be displayed then this alternate text will be displayed.
• height: It is used to specify the height of the image.
• width: It is used to specify the width of the image.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 4
Harish Kanchan II BCA C# and Dot Net Framework

• sizes: It is used to specify image sizes for different page layouts.


• srcset: It is used to specify a list of image files to use in different situations.

13. Write a note on HTML Form Tag.

Forms are required to take input from the user who visits the website. This form is used
basically for the registration process, logging into your profile on a website or to create
your profile on a website, etc … The information that is collected from the form is -1.
Name 2.Email Addresses etc. Now the form will take input from the form and post that
data in backend applications (like PHP). So the backend application will process the data
which is received by them. There are various form elements that we can use like text
fields, text area, drop-down list, select, checkboxes, radio, etc.
Syntax:
<form> Form Content... </form>
Attributes: There are many attributes that are associated with the <form> tag. Some of
them are listed below:
• Action Attribute: -This is used to send the data to the server after the submission of
the form.
• Method: -This is used to upload the data by using two methods that are Get and Post.
1. Get Method: -It has a limited length of characters of URL. -we should not use
get to send some sensitive data. -This method is better for non-secure data.
2. Post Method: -1. It has no size limitations 2. The submission of the form with
the method post, can not be bookmarked.
• Enctype attribute: -This attribute is used to specify that how a browser decodes the
data before it sends it to the server .so the values of this attribute are: -1.application/x-
www-formurlencoded − It is the standard method most forms used 2.multipart/form-
data -it is used when you have something to upload like files of images, word files, etc.
Example:An HTML form with two input fields and one submit button:
<form action="/action_page.php" method="get">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 5
Harish Kanchan II BCA C# and Dot Net Framework

14. What is Client-Side Scripts ?

1. Client-side scripting is responsible for interaction within a web page. The client-side
scripts are firstly downloaded at the client-end and then interpreted and executed by
the browser (default browser of the system).
2. The client-side scripting is browser-dependent. i.e., the client-side browser must be
scripting enables in order to run scripts
3. Client-side scripting is used when the client-side interaction is used. Some example
uses of client-side scripting may be :
• To get the data from user’s screen or browser.
• For playing online games.
• Customizing the display of page in browser without reloading or reopening the page.
4. Here are some popular client-side scripting languages VBScript, JavaScript, Hypertext
Processor (PHP).

15. What is Server-Side Scripts?

1. Server-side scripting is responsible for the completion or carrying out a task at the
server-end and then sending the result to the client-end.
2. In server-side script, it doesn’t matter which browser is being used at client-end,
because the server does all the work.
3. Server-side scripting is mainly used when the information is sent to a server and to
be processed at the server-end. Some sample uses of server-scripting can be :
• Password Protection.
• Browser Customization (sending information as per the requirements of client-end
browser)
• Form Processing
• Building/Creating and displaying pages created from a database.
• Dynamically editing changing or adding content to a web-page.
4. Here are some popular server-side scripting languages PHP, Perl, ASP (Active Server
Pages), JSP ( Java Server Pages).

16. How do you write comments in C#?

Comments play a very important role in the maintenance of programs. They are used to
enhance readability and understanding of code. All programs should have information
such as implementation details., change history and tasks performed. C# permits two
types of comments, namely,

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 6
Harish Kanchan II BCA C# and Dot Net Framework

• Single-line comments
• Multiline comments
Single-line comments begins with a double backslash(//) symbol and terminates at the
end of the line.
Multiline comments begins with /* characters and terminates with */ .
17. Define literals. List any two literal types used in C#.

Literals are value constants assigned to variables(or results of expressions) in a program.


C# supports several types of literals – Integer literals, Real Literals, Boolean literals,
String literals etc.

18. What do you mean by Boxing/Unboxing?

Boxing is a process of converting a value type variable to the reference type variable.
Boxing is implicit conversion process. Value type variables are always stored in Stack
memory, while reference type variables are stored in heap memory.
UnBoxing is a process of converting a reference type variable to the value type variable.
UnBoxing is explicit conversion process.

19. Write the syntax of conditional operator used in C# with an example.

The character pair ?: is a ternary operator available in C#. This operator is used to
construct conditional expressions of the form
exp1?exp2:exp3
where exp1,exp2 and exp3 are expressions.
The operator? : Works as follows: exp1 is evaluated first. If it is true, then the expression
exp2 is evaluated and becomes the value of the conditional expression. Only one of the
expressions (either exp2 or exp3) is evaluated. For example, consider the following
statements:
a=10;
b=15;
x=(a>b)?a:b;
In this example, x will be assigned the value of b. This can be achieved using the if..else
statement as follows:
if(a>b)
x=a;
else
x=b;

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 7
Harish Kanchan II BCA C# and Dot Net Framework

20. Differentiate break and continue statements used in C#?


The break statement is used to terminate the loop or statement in which it present. After
that, the control will pass to the statements that present after the break statement, if
available. If the break statement present in the nested loop, then it terminates only those
loops which contains break statement.
The Continue statement is used to skip over the execution part of the loop on a certain
condition. After that, it transfers the control to the beginning of the loop. Basically, it
skips its following statements and continues with the next iteration of the loop.
21. List the different types of Method Parameters used.
1.Value parameters 2.Output parameters
2.Reference parameters 4. Parameter arrays
22. Distinguish between ref and out parameters.
The ref is a keyword in C# which is used for the passing the arguments by a reference.
Or we can say that if any changes made in this argument in the method will reflect in
that variable when the control return to the calling method. The ref parameter does not
pass the property.
The out is a keyword in C# which is used for the passing the arguments to methods as
a reference type. It is generally used when a method returns multiple values. The out
parameter does not pass the property.
23. List any four method modifiers used.
1. public
2. private
3. protected
4. internal

24. What is variable size array ? Give example.


C# treats multidimensional arrays as 'arrays of arrays'. It is possible to declare a two-
dimensional
array as follows:
int[][] x= new int[3][]; //three rows array
x[0] = new int[2]; //first row has two elements
x[1] = new int[4]; //second row has four elements
x[2]= new int[3]; //third row has three elements
These statements create a two-dimensional array having different lengths for each row .
Variable-size arrays are called jagged arrays.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 8
Harish Kanchan II BCA C# and Dot Net Framework

25. List any four string methods in C#.


Compare() - Compares two strings
Compare To() - Compares the current instance with another instance
ConCat () - Concatenates two or more strings
Remove() - Deletes characters from
26. What is enumeration? How it defined in C#?
An enumeration is a user-defined integer type which provides a way for attaching names
to numbers, there by increasing the comprehensibility of the code. The enum keyword
automatically enumerates a list of words by assigning them values 0,1,2 and so on. This
facility provides an alternative means of creating ‘constant’ variable names.
Syntax: enum Shape {Cirlce, Square, Triangle}
27. Mention two differences between class and structure.

Long Answer Questions ( 4/5/6 Marks)

1. Explain HTML text formatting tags

HTML text formatting tags:


1) Bold Text: HTML<b> and <strong> formatting elements
The HTML <b> element is a physical tag which display text in bold font, without any logical
importance. If you write anything within <b>............</b> element, is shown in bold
letters.
Example: <p> <b> This is bold text.</b></p>

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 9
Harish Kanchan II BCA C# and Dot Net Framework

The HTML <strong> tag is a logical tag, which displays the content in bold font and informs
the browser about its logical importance. If you write anything between <strong>???????.
</strong>, is shown important text.
Example: <p><strong>This is an important content</strong>, and this is normal
content</p>
2) Italic Text: HTML <i> and <em> formatting elements
The HTML <i> element is physical element, which display the enclosed content in italic
font, without any added importance. If you write anything within <i>............</i> element,
is shown in italic letters.
Example: <p> <i>This is italic text.</i></p>
The HTML <em> tag is a logical element, which will display the enclosed content in italic
font, with added semantics importance.
Example: <p><em>This is an important content</em>, which displayed in italic font.
</p>
3) HTML Marked formatting: If you want to mark or highlight a text, you should write
the content within <mark>.........</mark>. Example: <h2> I want to put a <mark>
Mark</mark> on your face</h2>
4) Underlined Text: If you write anything within <u>.........</u> element, is shown in
underlined text.
Example: <p> <u> This is underlined text.</u></p>
5) Strike Text: Anything written within <strike>.......................</strike> element is
displayed with strikethrough. It is a thin line which cross the statement.
Example: <p> <strike>Text with strikethrough</strike>.</p>
6) Superscript Text: If you put the content within <sup>..............</sup> element, is
shown in superscript; means it is displayed half a character's height above the other
characters.
Example:<p>x<sup>2</sup> +y<sup>2</sup></p>
7) Subscript Text: If you put the content within <sub>..............</sub> element, is shown
in subscript ; means it is displayed half a character's height below the other characters.
Example:<p>H<sub>2</sub> O </p>

2. Explain HTML Table Tags with an example.

HTML table tag is used to display data in tabular form (row * column). There can be many
columns in a row.
We can create a table to display data in tabular form, using <table> element, with the help
of <tr> , <td>, and <th> elements.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 10
Harish Kanchan II BCA C# and Dot Net Framework

In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table
data is defined by <td> tags.
HTML tables are used to manage the layout of the page e.g. header section, navigation
bar, body content, footer section etc. But it is recommended to use div tag over table to
manage the layout of the page.
HTML Table Tags
Tag Description
<table> It defines a table.
<tr> It defines a row in a table.
<th> It defines a header cell in a table.
<td> It defines a cell in a table.
<caption> It defines the table caption
<colgroup> It specifies a group of one or more columns in a table for formatting.
<col> It is used with <colgroup> element to specify column properties for
each column.
<tbody> It is used to group the body content in a table.
<thead> It is used to group the header content in a table.
<tfooter> It is used to group the footer content in a table.
Example:
<table>
<tr> <th>Month</tr>
</tr>
<tr>
<td>January</td>
<td>rs.1000</td>
</tr>
</table>

3. Explain HTML Lists with an example.

HTML Lists are used to specify lists of information. All lists may contain one or more list
elements. There are three different types of HTML lists:
1. Ordered List or Numbered List (ol)
2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 11
Harish Kanchan II BCA C# and Dot Net Framework

• Unordered list – An unordered list starts with the <ul> tag. Each list item starts with the
<li> tag. The list items are marked with bullets typically small black circles
• Ordered list – An ordered list starts with the <ol> tag. Each list item starts with the <li>
tag.
The list items are marked with numbers.
• Definition lists - A definition list is a list of terms, with a description of each term.
Definition list values appear within <dl> and </dl> tag. It consists of two parts: Definition Term
<DT> and the Definition Description <DD>

Example : Illustration of unordered lists and Illustration of ordered lists and Illustration of
Definition lists

<html>

<body>

<p><b> My Favorite Actors are</b><p>

<ul type="circle">

<li> Mammuti

<li>Sudeep

<li>Salman Khan

<li> Vijay

</ul>

<p><b> My Favorite Actress are</b><p>

<OL type="A">

<li>Anushka shetty

<li>Aishwarya Rai

<li>Rakshitha

<li>Karina Kapoor

</OL>

<p><b> Components of Computer </b></p>

<dl>

<dt> Keyboard

<dd> It is an input device

<dt> Printer

<dd> It is an output device

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 12
Harish Kanchan II BCA C# and Dot Net Framework

</dl>

</body></html>

4. Explain HTML <frame> tag.

HTML <frame> tag define the particular area within an HTML file where another HTML
web page can be displayed.
A <frame> tag is used with <frameset>, and it divides a webpage into multiple sections or
frames, and each frame can contain different web pages.
Note: Do not use HTML <frame> tag as it is not supported in HTML5, instead you can use
<iframe> or <div> with CSS to achieve similar effects in HTML.
Syntax: < frame src = "URL" >

Example:

<html>

<head>

<title>Sidebar.html</title></head>

<frameset cols="25%,50%,25%">

<frameset rows="50%,50%">

<frame src="time.html">

<frame src="address.html">

</frameset>

<frame src="college.html">

<frame src="Link.html">

</frameset>

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 13
Harish Kanchan II BCA C# and Dot Net Framework

</html>

5. What are Advantages and Disadvantages of Client-side scripts?


Advantages
• Allow for more interactivity by immediately responding to users’ actions.
• Execute quickly because they do not require a trip to the server.
• May improve the usability of Web sites for users whose browsers support scripts.
• Can give developers more control over the look and behaviour of their Web widgets.
• Can be substituted with alternatives (for example, HTML) if users’ browsers do not
support scripts
• Are reusable and obtainable from many free resources.
Disadvantages
• Not all browsers support scripts, therefore, users might experience errors if no
alternatives have been provided.
• Different browsers and browser versions support scripts differently, thus more quality
assurance testing is required.
• More development time and effort might be required (if the scripts are not already
available through other resources).
• Developers have more control over the look and behaviour of their Web widgets; however,
usability problems can arise if a Web widget looks like a standard control but behaves
differently or vice-versa.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 14
Harish Kanchan II BCA C# and Dot Net Framework

6. What are Advantages and Disadvantages of server-side scripts?

Advantages:
• User can create one template for the entire website
• The site can use a content management system which makes editing simpler.
• Generally quicker to load than client-side scripting
• User is able to include external files to save coding.
• Scripts are hidden from view so it is more secure. Users only see the HTML output.
• User does not need to download plugins like Java or Flash.
Disadvantages:
• Many scripts and content management systems tools require databases in order to store
dynamic data.
• It requires the scripting software to be installed on the server.
• The nature of dynamic scripts creates new security concerns, in some cases making it
easier for hackers to gain access to servers exploiting code flaws.

7. Explain the structure of C# program.

Structure of C# Program

Documentation Section
Using Directive Section
Interfaces Section
Classes Section
Main Method (compulsory)
Example:
/* Program to show a simple
messege*/ using System;

namespace HelloFriendMsg

class HelloFriend

{ static void Main(string[] args)

/* my first program in C# */

Console.WriteLine("Hello Kanchan");

}
}
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 15
Harish Kanchan II BCA C# and Dot Net Framework

Output:
Hello Kanchan

Explanation:

• The first line of the program using System; - the using keyword is used to include
the System namespace in the program. A program generally has
multiple using statements.
• The next line has the namespace declaration. A namespace is a collection of classes. The
HelloFriendMsg namespace contains the class HelloFriendd.
• The next line has a class declaration, the class HelloFriend contains the data and method
definitions that your program uses. Classes generally would contain more than one method.
Methods define the behavior of the class. However, the HelloWorld class has only one
method Main.
• The next line defines the Main method, which is the entry point for all C# programs. The
Main method states what the class will do when executed
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program.
• The Main method specifies its behavior with the statement Console.WriteLine("Hello
Kanchan"); WriteLine is a method of the Console class defined in the System namespace.
This statement causes the message "Hello, Kanchan" to be displayed on the screen.

8. Explain Boxing and Unboxing with example.

Boxing and Unboxing:


In object-oriented programming, methods are invoked using objects. Since value types such as int and long
are not objects, we cannot use them to call methods. C# enables us to achieve this through boxing. Boxing means
the conversion of a value type on the stack to a object type on the heap. Conversely, the conversion from an object
type back to a value type is known as unboxing.

Boxing :
Any type, value or reference can be assigned to an object without an explicit conversion. When the
compiler finds a value type where it needs a reference type, it creates an object ‘box’ into which it places the value
of the value type.

Example:

int i = 12;
object box
= i; if (box is
int)

{
Console.Write("Box contains an int");

Unboxing:Unboxing is the process of converting the object type back to value type. Unboxing is an explicit
operation using C-style casting.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 16
Harish Kanchan II BCA C# and Dot Net Framework

Example: object box = 12;


//boxing int i =
(int)box; // unboxing

9. What are the various forms of ‘if’ statement? Explain with example.
The various forms of ‘if’ statements are:
1. Simple ‘if’ statement 2. if..else statement 3. Nested if..else statement 4.
else if statement
1. if Statement
if statement checks the given condition. If the condition evaluates to be true then the
block of code/statements will execute otherwise not.
Syntax:
if(condition)
{
//code to be executed
}

Ex:
if (20 > 18)
{
Console.WriteLine("20 is greater than 18");
}

2. if..else statement
if statement evaluates the code if the condition is true but what if the condition is not
true, here comes the else statement. It tells the code what to do when the if condition
is false.
Syntax:
if(condition)
{
// code if condition is true
}
else
{
// code if condition is false
}
Ex:

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 17
Harish Kanchan II BCA C# and Dot Net Framework

int a = 20;
if (a < 18)
{
Console.WriteLine("Good day."); }
else
{
Console.WriteLine("Good evening."); }

3. Nested if..else statement


if statement inside an if statement is known as nested if. if statement in this case is the
target of another if or else statement. When more than one condition needs to be true
and one of the condition is the sub-condition of parent condition, nested if can be used.
Syntax:
if (condition1)
{
// code to be executed
// if condition2 is true
if (condition2)
{
// code to be executed
// if condition2 is true
}}
Ex:
int i = 10, j = 20;

if (i != j)
{
if (i < j)
{
Console.WriteLine("i is less than j");
}
else if (i > j)
{
Console.WriteLine("i is greater than j");
}
}
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 18
Harish Kanchan II BCA C# and Dot Net Framework

else
Console.WriteLine("i is equal to j");

4. else if statement:
The if-else-if ladder statement executes one condition from multiple statements. The
execution starts from top and checked for each if condition. The statement of if block
will be executed which evaluates to be true. If none of the if condition evaluates to be
true then the last else block is evaluated.
Syntax:
if(condition1)
{
// code to be executed if condition1 is true
}
else if(condition2)
{
// code to be executed if condition2 is true
}
else if(condition3)
{
// code to be executed if condition3 is true
}
...
else
{
// code to be executed if all the conditions are false
}
Ex:
if (i == 10)
Console.WriteLine("i is 10");
else if (i == 15)
Console.WriteLine("i is 15");
else if (i == 20)
Console.WriteLine("i is 20");
else
Console.WriteLine("i is not present");

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 19
Harish Kanchan II BCA C# and Dot Net Framework

10. Explain the following loops with syntax and example.


i) while ii) do…while iii) for iv) foreach
i) while
The test condition is given in the beginning of the loop and all statements are executed
till the given boolean condition satisfies when the condition becomes false, the control
Ex:
will be out from the while loop.
int i = 0;
Syntax: while (i < 5)
while (condition) {
Console.WriteLine(i);
{
i++; }
// code block to be executed
}
ii) do…while
do while loop is similar to while loop with the only difference that it checks the condition
after executing the statements, i.e it will execute the loop body one time for sure because
Ex:
it checks the condition after executing the statements.
int i = 0;
Syntax :
do
do { Console.WriteLine(i);
{ i++; }
while (i < 5);
statements..
}while (condition);
iii) for
for loop has similar functionality as while loop but with different syntax. for loops are
preferred when the number of times loop statements are to be executed is known
beforehand. The loop variable initialization, condition to be tested, and
increment/decrement of the loop variable is done in one line in for loop thereby providing
a shorter, easy to debug structure of looping.
Syntax :
for (loop variable initialization ; testing condition; increment / decrement)
{
// statements to be executed
}
Ex:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i); }
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 20
Harish Kanchan II BCA C# and Dot Net Framework

iv) foreach
The foreach loop is used to iterate over the elements of the collection. The collection may
be an array or a list. It executes for each element present in the array.
Syntax:
foreach(data_type var_name in collection_variable)
{
// statements to be executed
}

Ex:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
11. Explain with syntax and example , how methods are declared in C#.

In C# a method declaration consists of the following components as follows :


Modifier : It defines access type of the method i.e. from where it can be accessed in your
application. In C# there are Public, Protected, Private access modifiers.
Name of the Method : It describes the name of the user defined method by which the
user calls it or refer it. Eg. GetName()
Return type: It defines the data type returned by the method. It depends upon user as
it may also return void value i.e return nothing
Body of the Method : It refers to the line of code of tasks to be performed by the method
during its execution. It is enclosed between braces.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 21
Harish Kanchan II BCA C# and Dot Net Framework

Parameter list : Comma separated list of the input parameters are defined, preceded
with their data type, within the enclosed parenthesis. If there are no parameters, then
empty parentheses () have to use out.

12. What are Method parameters? Explain the any two types.

Methods are defined as the code blocks or statements in a program that gives the user
the ability to reuse the same code, saving time, excessive memory use, and, more
importantly, providing better code readability. A method is a collection of statements that
perform some specific task and may or may not return the result to the caller function.
In certain situations, when the user wants to execute a method, but that method requires
some valuable inputs to execute and complete its tasks. These input values are known
as Parameters in computer language terms.
Types of Method Parameters:
Ref Parameters
The ref in C# is a keyword used to pass values by reference. The changes made to
the variables passed by reference in the called function reflects in the calling function.
The ref parameter doesn’t pass the property, and it is compulsory to initialise the
parameter before passing it.
Ex: void Modify(ref int x)
{
x+=10; // value of m will be changed
}
……..
int m=5; //m is initialized
Modify(ref m); // pass by reference
……..

Value Parameters
When values are passed instead of references, and the parameters contain data.
The changes made to the value parameter are not reflected on the variable in the calling
function.
Ex: static void Main(string[] args)
{
int a = 10;
int b = 25;
int res = Add(a, b);
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 22
Harish Kanchan II BCA C# and Dot Net Framework

}
public static int Add(int x, int y)
{
return x = y;
}

13. What are Parameter Arrays? Explain with example.

In C#, we can define methods that can handle variable number of arguments using what
are known as parameter arrays. Parameter arrays are declared using the keyword
params.
Ex:
void Function1(Params int [ ]x)
{
……..
…….
}
Here, x has been declared as a parameter array not that parameter arrays must be one
dimensional arrays a parameter may be a part of a formal and in such cases it must last
parameter the method function one defined above can be invoked in two ways:
1. Using int type array as a value parameter example: Function1(a). Here he is an array
of type int.
2. Using zero or more in the type arguments for the parameter array. Example:
Function1(10,20);
The second invocation creates and int type with two elements 10 and 20 and passes the
newly created array as the actual argument to the method.

14. With example explain declaring and initializing one dimensional and
twodimensional arrays in C#.

One Dimensional Array:


A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a one-dimensional array.
Declaration of one-dimensional array:
type[ ] arrayname;
Ex: int [ ] counter; // declare int array reference
float[ ] marks; //declare float array reference
int[ ] x,y; // declare two int array reference
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 23
Harish Kanchan II BCA C# and Dot Net Framework

After declaring an array, we need to create it in the memory. C# allows to create arrays
using new operator.
arrayname=new type[size];
Example: number=new int[5]; //create a 5 element int array
average=new float[10]; //create a 10 element float array
Initialization of one-dimensional Array
The Final step is to put values into the array created. This process is known as
initialization. This is done using the array subscripts.
arrayname[subscript]=value;
Example: int[ ] number={35,40,20,57,19}
The array initializer is a list of values separated by commas and defined on both ends by
curly braces. Note that no size is given. The compiler allocates enough space for all the
elements specified in the list.
Two Dimensional Array:
A two-dimensional array consists of single-dimensional arrays as its elements. It can be
represented as a table with a specific number of rows and columns.
Declaration of Two Dimensional Array:
int[ , ] x = new int [2, 3];
Here, x is a two-dimensional array with 2 elements. And, each element is also an array
with 3 elements.
So, all together the array can store 6 elements (2 * 3).
Two-Dimensional Array initialization
In C#, we can initialize an array during the declaration. example,
int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };
Here, x is a 2D array with two elements {1, 2, 3} and {3, 4, 5}. We can see that each
element of the array is also an array.
We can also specify the number of rows and columns during the initialization.
Example,
int [ , ] x = new int[2, 3]{ {1, 2, 3}, {3, 4, 5} };

15. Explain any three string methods in C# with example.

There are several methods present in the String class. These methods help in working
with different string objects.
Copy( ) method
We can create new copies of existing strings. This can be accomplished in two ways:
• using the overloaded=operator
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 24
Harish Kanchan II BCA C# and Dot Net Framework

• using the static Copy method


Example: string s2=s1; //assigning
string s2=string.Copy(s1); // copying
Both these statements would accomplish the same thing, namely, copying the contents
of s1 into s2.
Concatenating strings:
We may also create new strings by concatenating existing strings. There are a couple of
ways to accomplish this.
• Using the overloaded+operator
• Using the static Concat method.
Example: string s3=s1+s2; //s1 and s2 exist already
string s3=string.Concat(s1,s2)
If s1=’abc’ and s2=’xyz’, then both the statements will store the string ‘abcxyz’ in s3. Note
that the contents of s2 is simply appended to the contents of s2 and the result is stored
in s3.
Equals() method
The string class supports an overloaded Equals method for testing the equality of strings.
There are again two versions of Equals methods. They are implemented as:
bool b1=s2.Equals(s1);
bool b2=string.Equals(s2,s1);
These methods return a Boolean value true if s1 and s2 are equal, otherwise false.

16. With example explain enumeration declaration and initialization in C#.

An Enumeration is a user – defined integer type which provides a way for attaching names to
numbers, thereby increasing the comprehensibility of the code. The enum keyword
automatically enumerates a list of words by assigning them values 0,1,2 and so on. This facility
provides an alternative means of creating ‘constant’ variable names.
Syntax:
enum Shape
{
Circle, //ends with comma
Square, //ends with comma
Triangle //no comma
}
This can be written in one line as follows:
enum Shape{Circle, Square, Triangle}
Here, Circle has the value 0, Square has the value 1 and Triangle has the value 2.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 25
Harish Kanchan II BCA C# and Dot Net Framework

UNIT -2
Two Mark Questions
1. List types of constructors in C#.
• Default constructor
• Parameterized constructor
• Copy constructor
• Static constructor
• Private constructor
2. What do you mean by overloaded constructors?
Overloaded constructors can be used to instantiate objects in exactly the same manner
as for classes with a single constructor. During compilation of the code, the compiler
compares the signature used for the new object to those available in the class. If there is
a perfect match, the corresponding constructor is used. Where there is no signature with
the correct parameters, the compiler will look for a constructor that can be used with
implicit casting. If no such constructor exists, a compiler error occurs.
3. What are Static constructors?
A static constructor is called before any object of the class is created. It is usually used to
assign initial values to static data members.
A static constructor is declared by prefixing a static keyword to the constructor definition.
It cannot have any parameters.
Example:
class Abc
{
static Abc( ) // No parameters
{
….. // set values for static members here
}…..
Note that there is no access modifier on static constructors. It cannot take any. A class
can have only one static constructor.
4. What do you mean by polymorphism?
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
In c#, polymorphism provides an ability for the classes to implement different methods
called through the same name. It also provides an ability to invoke a derived class's
methods through base class reference during runtime based on our requirements.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 26
Harish Kanchan II BCA C# and Dot Net Framework

5. What do you mean by copy constructor?


A copy constructor creates an object by copying variables from another object. For
example, we may wish to pass an item object to the item constructor so that the new item
object has the same values as old one. Since C# does not provide a copy constructor, we
must provide it ourselves if we wish to add this feature to the class. A copy constructor is
defined as follows:
public item(item item)
{
code=item.code;
price=item.price;
}

6. What do you mean by destructors? How they are defined in C#?


Destructor is a method called when an object is no more required. The name of the
destructor is the same as the class name and is preceded by a tilde (~). Like constructors,
a destructor has no return type.
Ex:
class Fun
{
……
~Fun( ) //No arguments
{
……
}
7. What do you mean by „this‟ reference in C#?
C# supports the keyword this which is a reference to the object that called the method.
The this reference is available within the member methods and always refers to the
current instance. It is normally used to distinguish between local and instance variables
that have the same name.
class Integers
{
int x,y;
public void SetXY(int x, int y)
{
this.x=x;
this.y=y; }
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 27
Harish Kanchan II BCA C# and Dot Net Framework

8. Differentiate constant member & read-only members used in C#.

9. Give the syntax and example for interface in C# .


Interface in C# is a blueprint of a class. It is like abstract class because all the methods
which are declared inside the interface are abstract methods. It cannot have method body
and cannot be instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to
achieve fully abstraction because it cannot have method body.
Syntax:
interface interfacename
{
Member declarations;
}
Ex:
interface inter1
{
void display(); // method having only declaration not definition
}
class testClass : inter1 // A class that implements interface
{
public void display() // providing the body part of function
{
Console.WriteLine("C# Programming");
}

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 28
Harish Kanchan II BCA C# and Dot Net Framework

10. What is operator overloading?


Operator overloading gives the ability to use the same operator to do various operations.
It provides additional capabilities to C# operators when they are applied to user-defined
data types. It enables to make user-defined implementations of various operations where
one or both of the operands are of a user-defined class.
Only the predefined set of C# operators can be overloaded. To make operations on a
user-defined data type is not as simple as the operations on a built-in data type. To use
operators with user-defined data types, they need to be overloaded according to a
programmer’s requirement. An operator can be overloaded by defining a function to it.
The function of the operator is declared by using the operator keyword.
11. List any four operators that cannot be overloaded.
= , . , ?: , -> , new, is, sizeof, typeof
These operators cannot be overloaded.
12. Give the syntax of defining operator function.
An operator can be overloaded by defining a function to it. The function of the operator
is declared by using the operator keyword.
Syntax :
access specifier className operator Operator_symbol (parameters)
{
// Code
}

13. What is a Delegate ? What is it used for?


A delegate object is a special type of object that contains the details of a method rather
than data.
Delegates in C# are used for two purposes:
Callback
Event Handling
Dictionary meaning of delegate is “a person acting for another person”, in C# it means a
method acting for another method.
A delegate in C# is a class type object & is used to invoke a method that has been
encapsulated into it at the time of its creation.
14. What is delegate method?
The methods whose references are encapsulated into a delegate instance are known as
delegate methods or callable entities. The signature and return type of delegate methods
must exactly match the signature and return type of the delegate.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 29
Harish Kanchan II BCA C# and Dot Net Framework

15. List the steps involved in creating and using a delegates.


• Delegate declaration
• Delegate methods definition
• Delegate instantiation
• Delegate invocation

16. What is an Event in C# ? Give the syntax of event declaration.


An event is a delegate type class member that is used by the object or class to provide a
notification to other objects that an event has occurred. The client object can act on an
event by adding an event handler to the event.

17. List any four built in exceptions in C#.


ArgumentException Raised when a non-null argument that is passed
to a method is invalid.
ArgumentNullException Raised when null argument is passed to a
method.
ArgumentOutOfRangeException Raised when the value of an argument is outside
the range of valid values.
DivideByZeroException Raised when an integer value is divide by zero.

18. What is use of finally() block in exception handling ?


The finally block will execute when the try/catch block leaves the execution, no matter
what condition cause it. It always executes whether the try block terminates normally or
terminates due to an exception. The main purpose of finally block is to release the system
resources. The finally block follows try/catch block.

19. What is VB IDE?


IDE is the work setting to create Visual Basic applications. This helps to develop, run,test
and debug applications. Visual Basic provides a graphical environment in which
theprogrammer can visually design the forms and other controls that become the
building block of the application.IDE is a term commonly used in the programming world
to describe the interface andenvironment that we use to create our applications. It is
called integrated, because we canaccess virtually all of the development tools that we
need from one screen, called an interface.

20. List any four components of VB IDE.


• Toolbar
• Menu bar
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 30
Harish Kanchan II BCA C# and Dot Net Framework

• Form Designer
• Properties window

21. What do you mean by properties in VB.net?


All the Visual Basic Objects can be moved, resized or customized by setting their
properties. A property is a value or characteristic held by a Visual Basic object, such as
Caption or Fore Color.
Properties can be set at design time by using the Properties window or at run time by
using statements in the program code.
22. What is Intellisence? List any two features.
Intellisence is a code completion tool that is built into Microsoft Visual Studio. It is one
of a number of similar tools that allow for intelligent code completion ot intelligent text
completion on different platforms.
Intellisence is useful because it tells you what syntax is correct automatically, or lists all
the members of an object that are available.
23. What is the significance of component tray?
The component tray is a rectangular region displayed at the bottom of the design view
window while in design view mode, once it is active. The component tray becomes active
in design view after a component that is displayed in the component tray has been added
to or is part of the current document.
The component tray provides a way for users to access and set the properties of those
components. Some types of components, such as a Timer, may not have a user interface
that can be viewed at design time.

24. List any four tools available in toolbox.


• Text Box
• Label
• Button
• Combo Box

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 31
Harish Kanchan II BCA C# and Dot Net Framework

Long Answer Questions ( 4/5/6 Marks)

1. With syntax and example, explain how class is defined and used in a program.
A class is a user defined data type with a template that serves to define its properties.
Once the class type has been defined, we can create ‘variables’ of that type using
declarations that are similar to the basic type declarations.
In C#, these variables are termed as instances of classes, which are actual objects.
The basic form of class definition is
class classname
{
[variable declaration;]
[methods declaration;]
}
class is a keyword and classname is any valid C# identifier.
Example:
class Rectangle
{
int length; //instance variable
int width; // instance variable
}

2. Explain concept of Static members and methods with example.


To define a member that is common to all the objects and accessed without using a
particular object. That is, the member belongs to the class as a whole rather than the
objects created from the class. Such members can be defined as follows.
static int count;
static int max,
A static method is declared with the help of static keyword. Static methods are accessed
with the name of the class. A static method can access static and non-static fields, static
fields are directly accessed by the static method without class name whereas non-static
fields require objects.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 32
Harish Kanchan II BCA C# and Dot Net Framework

3. What is Constructor? Explain any 2 types of constructors in C#.


A constructor is a special method of the class which gets automatically invoked
whenever an instance of the class is created. Like methods, a constructor also contains
the collection of instructions that are executed at the time of Object creation. It is used
to assign initial values to the data members of the same class.
A copy constructor creates an object by copying variables from another object. For
example, we may wish to pass an item object to the item constructor so that the new
item object has the same values as old one. Since C# does not provide a copy
constructor, we must provide it ourselves if we wish to add this feature to the class. A
copy constructor is defined as follows:
public item(item item)
{
code=item.code;
price=item.price;
}
A static constructor is called before any object of the class is created. It is usually used
to assign initial values to static data members.
A static constructor is declared by prefixing a static keyword to the constructor
definition. It cannot have any parameters.
Example:
class Abc
{
static Abc( ) // No parameters
{
….. // set values for static members here
}…..
Note that there is no access modifier on static constructors. It cannot take any. A class
can have only one static constructor.
4. Write a note on constructor overloading.
Constructor overloading is a technique to define multiple constructors within a class
with different sets of parameters to achieve polymorphism. We can overload
constructors in C# just like methods. We can do so by changing the signatures by using
a different number, or type of parameters
We can overload constructors in different ways as follows:
By using different type of arguments
By using different number of arguments

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 33
Harish Kanchan II BCA C# and Dot Net Framework

By using different order of arguments


Ex:
class Room
{
public double length,breadth;
public Room(double x, double y) //constructor 1
{
length=x;
breadth=y;
}
public Room(double x) //constructor 2
length=breadth=x;
}
public int Area( )
{
return(length*breadth);
}
}
5. Explain multi-level inheritance with example.
A common requirement in object-oriented programming is the use of a derived class as
a superclass. C# supports this concept and uses it extensively in building its class
library.
The class A serves as a base class for the derived class B which in turn serves as a base
class for
the derived class C. The chain ABC is known as inheritance
path.
A derived class with multilevel base classes is declared as
follows:
class A
{
......
......
}
class B : A // First level derivation
{
......

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 34
Harish Kanchan II BCA C# and Dot Net Framework

......
}
class C:B // Second level derivation
{
........
.........
}
This process may be extended to any number of levels. The class C can inherit the
members of both A and B.
Example:
Class A
{
protected int a;
public A (int x)
{
a = x;
}
}
class B:A
{
protected int b;
public B (int x, int y): base (x)
b = y;
}
}
class C:B
{
int c;
public C (int x, int y, int z) : base (x, y)
{
c = z;
}
}

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 35
Harish Kanchan II BCA C# and Dot Net Framework

6. Write note on class member visibility.


A class member can have any one of the five visibility modifiers:
• Public
• protected
• Private
• Internal
• protected internal
When no modifier is specified, it defaults to private accessibility.

protected - members can only be reached from within the same class, or from a class
which inherits from this class.
internal - members can be reached from within the same project only.
protected internal - the same as internal, except that classes which inherit from this
class can reach its members; even from another project.
private - can only be reached by members from the same class. This is the most
restrictive visibility. Classes and structs are by default set to private visibility.
7. What is Interface? Explain the defining , extending and implementing interface.
Interface in C# is a blueprint of a class. It is like abstract class because all the methods
which are declared inside the interface are abstract methods. It cannot have method body
and cannot be instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to
achieve fully abstraction because it cannot have method body.

Defining an interface
The syntax for defining an interface is very similar to that used for defining a class.
The general form of an interface definition is
interface InterfaceName
{
Member declarations;
}

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 36
Harish Kanchan II BCA C# and Dot Net Framework

Here, interface is the keyword and Interface Name is a valid C# identifier (just like class
names). Member declarations will contain only a list of members without implementation
code.
Extending an Interface
C# allows an interface to extend one or more interfaces. The following example illustrates
how to define an interface that extends another interface:

First, define the IUndoable interface that has one method Undo():
interface IUndoable
{
void Undo();
}
Second, define the IRedoable interface that extends the IUndoable interface:
interface IRedoable : IUndoable
{
void Redo();
}
In this example, the IRedoable interface inherits all the members of the IUndoable
interface. In other words, a class that implements the IRedoable interface must also
provide implementations for Redo() method in the IRedoable interface and the Undo()
method of the IUndoable interface.

Third, define the Input class that implements the IRedoable interface:
class Input : IRedoable
{
public void Redo()
{
Console.WriteLine("Redo");
}

public void Undo()


{
Console.WriteLine("Undo");
}
}
Finally, create an instance of the Input class and call the Undo() and Redo() methods:

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 37
Harish Kanchan II BCA C# and Dot Net Framework

var input = new Input();


input.Undo();
input.Redo();
Implementing an Interface
A class or a Struct can implement one or more interfaces using colon :. On impmenting
an interface, you must override all the members of an interface.
Syntax:
class ClassName : InterfaceName
{
…..
}
For example, the following FileInfo class implements the IFile interface, so it should
override all the members of IFile.
Example: Interface Implementation
interface IFile
{
void ReadFile();
void WriteFile(string text);
}
class FileInfo : IFile
{
public void ReadFile()
{
Console.WriteLine("Reading File");
}
public void WriteFile(string text)
{
Console.WriteLine("Writing to file");
}
}
In the above example, the FileInfo class implements the IFile interface. It overrides all the
members of the IFile interface with public access modifier. The FileInfo class can also
contain members other than interface members.
8. Write a note on rules for overloading unary and binary operators.
a)Overloading unary operator.
b)Overloading binary operator.
c)Overloading binary operator using a friend function.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 38
Harish Kanchan II BCA C# and Dot Net Framework

Below are some criteria/rules to define the operator function:

• In case of a non-static function, the binary operator should have only one
argument and unary should not have an argument.
• In the case of a friend function, the binary operator should have only two
argument and unary should have only one argument.
• All the class member object should be public if operator overloading is
implemented.
• Operators that cannot be overloaded are . .* :: ?:
• Operator cannot be used to overload when declaring that function as friend
function = () [] ->.

9. Explain Unary operator overloading with example.


A minus operator, when used as unary, takes just one argument . We know that this
operator changes the sign of an operand when applied to a basic data item. We shall
see here how to overload this operator so that it can be applied to an object in much
the same way as is applied to an int or float variable. The unary minus when applied to
an object should change the sign of each of its data items.
The method operator -( ) takes one argument of type Space and changes the sign of data
members of the object s. Since it is a member method of the same class, it can directly
access the members of the object which activated it. Remember, a statement like
s2 = -s1;
will not work, because the operator method does not return any value. It can work
if the method is modified to return an object
Ex:
using System;
class Space
{
int x, y, z;
public Space (int a, int b, int c)
{
x = a;
y = b;
z = c;
}
public void Display ()
{
Console.Write(" " + x);
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 39
Harish Kanchan II BCA C# and Dot Net Framework

Console.Write(" "+y);
Console.Write("" + z);
Console.WriteLine();
}
public static Space operator - (Space s)
{
s.x = -s.x;
s.y = -s.y:
s.z= -s.z;
}
}
class SpaceTest
{
public static void Main()
{
Space s = new Space (10, -20, 30 );
Console.Write("s:");
s. Display();
-s; //activates opeator -() method
Console.Write("s: ");
s. Display();
}
}
10. Explain binary operator overloading with example.
An operator which contains two operands to perform a mathematical operation is
called the Binary Operator Overloading. We can always use methods to add two
objects.
A statement like C = sum (A, B); //functional notation
is possible. The functional notation can be replaced by a natural looking expression
C = A + B; //arithmetic notation.
by overloading the + operator using an operator +() method. Here is the syntax used to
define the operator +() method.
public static Vector operator + (Vector u1, Vector u2)
{
//Create a new Vector object
// Add the contents of u1 and

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 40
Harish Kanchan II BCA C# and Dot Net Framework

u2 //to the new Vector object


// Return the new vector object
}
This program overloads the binary plus operator to add two complex numbers of type:
X = a + jb
Ex:
using System;
class Complex
{
double x; //real part
double y; //imaginary part
public Complex ()
{
}
public Complex(double real, double imag)
x = real;
y = imag;
}
public static Complex operator + (Complex c1, Complex c2)
{
Complex c3 = new Complex ();
c3.x = C1.x + c2.x;
c3.y = C1.y + c2.y;
return (c3);
}
public void Display()
{
Console.Write(x);
Console.Write(“ + j” + y);
Console.WriteLine();
}
}
class ComplexTest
{
public static void Main()
{

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 41
Harish Kanchan II BCA C# and Dot Net Framework

Complex a, b, c;
a = new Complex (2.5, 3.5);
b = new Complex (1.6, 2.7);
C = a + b;
Console.Write(" a = ");
a.Display();
Console.Write("b = ");
b.DisplayO;
Console.Write("c=");
c. Display();
}
}
11. Explain with syntax and example, how delegates are declared.
A delegate object is a special type of object that contains the details of a method rather
than data.
Delegate Declaration
General Form:
modifier delegate return-type delegate-name(parameters);
Delegate is derived from System. Delegate class. The modifier controls the
accessibility of the delegate.
Delegate may take any of the following modifiers: new, public, private, protected,
internal.
It is a class type & can be declared in any place where a class definition is permitted.
A delegate may be defined in the following places:
Inside a class
Outside all classes
As the top level object in a namespace.
Ex:
public delegate int MyDelegate (string s);
delegate void simpledelegate();
private delegate int mydelegate(object o1, object o2);
12. Write note on delegate methods.
• The methods whose references are encapsulated into a delegate instances are known
as delegate methods (or callable entities)
• The signature & return type of delegate methods must exactly match the signature
& return type of the delegate.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 42
Harish Kanchan II BCA C# and Dot Net Framework

Ex:
delegate double mathop(double x, double y);
public static double multiply(double a, double b)
{ return(a*b);}
public double divide(double a, double b)
{ return (a/b);}

13. Write a note on delegate instantiation and invocation.


Delegate Instantiation
A delegate-creation-expression is used to create a new instance of a delegate.
General Form:
new delegate-type(expression)
• Here the delegate -type is the name of the delegate declared earlier whose object
is to be created.
• Expression must be the method name.
The method & the object to which a delegate refers are determined when the delegate
is instantiated. This remains constant for the entire lifetime of the delegate.
It is not possible to change them, once the delegate is created.

Ex: delegate int productDelegate(int x, int y);


class Delegate
{
static float product (float a, float b) //signature does not match
{ return(a*b);}
static int product(int a, int b) // signature matches
{ return (a*b);}
}
productdelegate p=new productdelegate(product); //delegate
instantiation
Delegate Invocation
When a delegate is invoked, it in turn invokes the method whose reference has been
encapsulated
into the delegate.
General Form:
delegate_object (parameter list);

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 43
Harish Kanchan II BCA C# and Dot Net Framework

– The optional parameter list provides values for the parameters of the method to be
used.
Ex:delegate1(x , y);
int x=delegate1(2,4);

14. With syntax and example explain exception handling mechanism in C#.
An exception is an error that occurs during program execution. Generally, an exception
describes an unexpected event.
An exception is a condition that is caused by a run-time error in the program.
The purpose of the exception handling mechanism is to provide a means to detect and
report on exceptional circumstances, so that appropriate action can be taken.
Syntax of Exception Handling
C# provides a code structure known as the try / catch block that permits the handling
of
exceptions. A basic try / catch block has two elements. The try section contains one
or more commands to be executed, held within brace characters { }. The catch section
contains code to execute if an exception occurs during processing of the try section.
try
{
// commands to execute whilst checking for exceptions
}
catch
{
// commands to execute if an exception occurs
}
Ex:
try
{
calculated = value / divisor;
}
catch (Exception ex) // Catch any exception
{
Console.WriteLine("An error occurred during division.");
Console.WriteLine(ex.Message); // Report the error message
calculated = value / 10;
}

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 44
Harish Kanchan II BCA C# and Dot Net Framework

Console.WriteLine("Result = {0}", calculated);


}

15. Explain following components of VBIDE


i) Project Explorer ii) Toolbox iii) properties window
i) Project Explorer
• This displays a hierarchical list of the projects and all of the items contained and
referenced by each project.
• It will appear in the top left corner of the application by default.
• This can be displayed with the shortcut key (Ctrl + R).
• You can enter a property's value in the right column. For those properties that
have a predefined set of values, choose the value and then select one from the
values displayed in the list box.
ii) Toolbox
• The Toolbox window contains all the controls you can use to build your application’s
interface.
• This window is usually retracted, and you must move the pointer over it to view the
Toolbox.
• The controls in the Toolbox are organized in various tabs, so take a look at them to
become familiar with the controls and their functions.
• It is used to accept textual input from the user. The user can add strings, numerical
values and a combination of those, but Images and other multimedia content are
not supported.
iii) Properties window
• Properties window to contain a set of properties for the selected Object or controls
properties are the characteristics of an Object such as its size, caption, color and so
on.
• This window (also known as the Properties Browser) displays all the properties of
the selected component and its settings. Every time you place a control on a form,
you switch to this window to adjust the appearance of the control.
• You can open the properties window for a particular Object by selecting it and
choosing view properties from the menu bar. You can also change the appearance
of the Object on the form through properties window.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 45
Harish Kanchan II BCA C# and Dot Net Framework

16. Explain following components of VBIDE


i) Code window ii) Solution explorer iii) Component tray
i) Code window
• Code window is used to write, display, and edit Visual Basic code.
• You can open as many Code windows as you have modules, so you can easily view
the code in different forms or modules, and copy and paste between them.
• You can open a Code window from: The Project window, by selecting a form or
module, and choosing the View Code button.
• A UserForm window, by double-clicking a control or form, choosing Code from the
View menu, or pressing F7.

ii) Solution explorer


• This displays the solution name, project name, form name, module name and all
other files associated with the project.
• The Solution Explorer window contains a list of the items in the current solution.
• A solution can contain multiple projects, and each project can contain multiple
items.
• The Solution Explorer displays a hierarchical list of all the components,
organized by project.
iii) Component tray
• The component tray is a rectangular region displayed at the bottom of the design
view window while in design view mode, once it is active.
• The component tray becomes active in design view after a component that is
displayed in the component tray has been added to or is part of the current
document.
• The component tray provides a way for users to access and set the properties of
those components. Some types of components, such as a Timer, may not have a
user interface that can be viewed at design time.
17. Explain following components of VBIDE
i ) Graphical Designers ii) Dynamic Help window
i ) Graphical Designers
• It allows you to design the user interface for an application and add controls to
a form, arrange them and add code to perform some action. It provides you with
a rapid development solution for our application.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 46
Harish Kanchan II BCA C# and Dot Net Framework

• Windows Forms Designer lets you easily add controls to a form, arrange them,
and write code for their events. For more information about Windows Forms, see
Windows Forms overview.
ii) Dynamic Help window
• It provides you with context sensitive help.
• The Dynamic Help window automatically displays appropriate Help links to the
. NET Help files, depending on where the cursor is and what text is highlighted.
• As you move from one window to another within the IDE, information displayed
in the Dynamic Help window changes.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 47
Harish Kanchan 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.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 48
Harish Kanchan 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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 49
Harish Kanchan II BCA C# and Dot Net Framework

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

=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.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 50
Harish Kanchan 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 where as in labels you don’t 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 MyTextBox As New TextBox()

MyTextBox.Size = New Size(148, 23)


MyTextBox.Location = New Point(53, 39)
MyTextBox.Text = "Hi Friend"
Me.Controls.Add(MyTextBox)

End Sub

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

Ans:

Gets or sets a value specifying if the control should be automatically 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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 51
Harish Kanchan II BCA C# and Dot Net Framework

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.

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"
Me.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());
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 52
Harish Kanchan II BCA C# and Dot Net Framework

VB. Net Code


TextBox1.Text = ListBox1.SelectedIndex
TextBox2.Text = ListBox1.SelectedItem

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

Combobox1.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
Dim count As Integer
count = ComboBox1.Items.Count()
TextBox1.Text = 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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 53
Harish Kanchan II BCA C# and Dot Net Framework

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.

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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 54
Harish Kanchan II BCA C# and Dot Net Framework

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.

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 55
Harish Kanchan II BCA C# and Dot Net Framework

Byte 1 byte 0 to 255

Char 2 bytes 0 to 65535

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


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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 56
Harish Kanchan II BCA C# and Dot Net Framework

Defined Platform has a range determined by its


data type and is independent of
the ranges of the other members

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 57
Harish Kanchan II BCA C# and Dot Net Framework

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 58
Harish Kanchan II BCA C# and Dot Net Framework

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.

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 −

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 59
Harish Kanchan II BCA C# and Dot Net Framework

Do { While | Until } condition


[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
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 ]

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 60
Harish Kanchan II BCA C# and Dot Net Framework

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

Example:

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 61
Harish Kanchan II BCA C# and Dot Net Framework

Sub Main()
Dim intValue As Integer = 1
If intValue = 1 Then
Dim strText As String = "No worries."
System.Console.WriteLine(strText)
End If
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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 62
Harish Kanchan II BCA C# and Dot Net Framework

Label1 = New Label


Label1.AutoSize = True
Label1.Location = New Point(15, 15)
:
:
:
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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 63
Harish Kanchan II BCA C# and Dot Net Framework

Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 64
Harish Kanchan II BCA C# and Dot Net Framework

Array can be resized according to the program's requirements at run time using the
"ReDim" statement..

Syntax of ReDim:

ReDim [Preserve] varname(subscripts)

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:
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 65
Harish Kanchan II BCA C# and Dot Net Framework

You declare Sub procedures with the Sub statement:

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


[ statements ]
[ Exit Sub ]
[ statements ]
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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 66
Harish Kanchan II BCA C# and Dot Net Framework

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.

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)

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 67
Harish Kanchan II BCA C# and Dot Net Framework

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 68
Harish Kanchan II BCA C# and Dot Net Framework

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.

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()

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 69
Harish Kanchan II BCA C# and Dot Net Framework

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

End Sub

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 indicating if the form is visible.

13. Explain MsgBox Function with an example.


Syntax

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


Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 70
Harish Kanchan II BCA C# and Dot Net Framework

= 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

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 71
Harish Kanchan II BCA C# and Dot Net Framework

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.

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 button
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 button is
released.
MouseWheel— Happens when the mouse wheel moves while the control has focus.
Example 1:

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 72
Harish Kanchan II BCA C# and Dot Net Framework

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
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 a
single-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();

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 73
Harish Kanchan II BCA C# and Dot Net Framework

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


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);

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 74
Harish Kanchan II BCA C# and Dot Net Framework

text_box1.Text= “HARISH KANCHAN”;


}
}
}

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 75
Harish Kanchan 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()
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 76
Harish Kanchan II BCA C# and Dot Net Framework

End Sub

'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
'removing the All items from the ListBox
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
ListBox1.Items.Clear()
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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 77
Harish Kanchan II BCA C# and Dot Net Framework

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.(Question Removed)

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

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 78
Harish Kanchan II BCA C# and Dot Net Framework

PROPERTY DESCRIPTION

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.

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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 79
Harish Kanchan II BCA C# and Dot Net Framework

PROPERTY DESCRIPTION

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.

21.What is use of Progress bar control ? Explain its unique properties.(Question


Removed)
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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 80
Harish Kanchan II BCA C# and Dot Net Framework

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
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:

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 81
Harish Kanchan II BCA C# and Dot Net Framework

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.

// To remove item with index 0:


comboBox1.Items.RemoveAt(0);
// To remove currently selected item:
comboBox1.Items.Remove(comboBox1.SelectedItem);
// To remove "BBA" 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.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 82
Harish Kanchan II BCA C# and Dot Net Framework

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.

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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 83
Harish Kanchan II BCA C# and Dot Net Framework

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.

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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 84
Harish Kanchan II BCA C# and Dot Net Framework

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

• 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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 85
Harish Kanchan II BCA C# and Dot Net Framework

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.

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 86
Harish Kanchan II BCA C# and Dot Net Framework

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

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 87
Harish Kanchan II BCA C# and Dot Net Framework

• 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 .

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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 88
Harish Kanchan II BCA C# and Dot Net Framework

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

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 89
Harish Kanchan II BCA C# and Dot Net Framework

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

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 90
Harish Kanchan II BCA C# and Dot Net Framework

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

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 91
Harish Kanchan II BCA C# and Dot Net Framework

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

5.Explain SqlConnection Class

6.Explain SqlCommand Class

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 92
Harish Kanchan II BCA C# and Dot Net Framework

7.Explain SqlDataAdapter Class

8.Explain DataSet Class

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 93
Harish Kanchan II BCA C# and Dot Net Framework

9. Explain SqlDataReader Class

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 94
Harish Kanchan II BCA C# and Dot Net Framework

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
v. The CustomValidator control
vi. The ValidationSummary control
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 95
Harish Kanchan II BCA C# and Dot Net Framework

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

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

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 96
Harish Kanchan II BCA C# and Dot Net Framework

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

validation syntax is different on the client than on the server.


JScript is used on the client. On the server, the language
you have specified is used

Output:

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 97
Harish Kanchan II BCA C# and Dot Net Framework

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,
being validated
ValueToCompare Lessthan
Sets a constant value to compare with the value entered by the
user

in the input control being validated

Output:

The CustomValidator Control


Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 98
Harish Kanchan II BCA C# and Dot Net Framework

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

• List

• SingleParagraph
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 99
Harish Kanchan II BCA C# and Dot Net Framework

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

ForeColor enabled
The fore or notof the control
color
HeaderText A header in the ValidationSummary control
ShowMessageBox A Boolean value that specifies whether the summary should be

ShowSummary displayed
A Booleanin a message
value box or whether
that specifies not the ValidationSummary

Output: control should be displayed or hidden

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


Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 100
Harish Kanchan 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.

Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 101

You might also like