C# Dot Net Solved QB
C# Dot Net Solved QB
C# Dot Net Solved QB
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).
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.
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.
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?
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 1
Harish Kanchan II BCA C# and Dot Net Framework
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.
• 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
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.
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
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
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
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
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).
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).
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#.
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.
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
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 8
Harish Kanchan II BCA C# and Dot Net Framework
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>
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>
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>
<ul type="circle">
<li> Mammuti
<li>Sudeep
<li>Salman Khan
<li> Vijay
</ul>
<OL type="A">
<li>Anushka shetty
<li>Aishwarya Rai
<li>Rakshitha
<li>Karina Kapoor
</OL>
<dl>
<dt> Keyboard
<dt> Printer
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>
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>
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 14
Harish Kanchan II BCA C# and Dot Net Framework
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.
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
/* 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.
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
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."); }
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
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#.
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;
}
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#.
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} };
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
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
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 28
Harish Kanchan II BCA C# and Dot Net Framework
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 29
Harish Kanchan II BCA C# and Dot Net Framework
• Form Designer
• Properties window
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 31
Harish Kanchan II BCA C# and Dot Net Framework
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
}
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 32
Harish Kanchan II BCA C# and Dot Net Framework
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 33
Harish Kanchan II BCA C# and Dot Net Framework
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
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");
}
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 37
Harish Kanchan II BCA C# and Dot Net Framework
• 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 = () [] ->.
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
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);}
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
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 45
Harish Kanchan II BCA C# and Dot Net Framework
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
[ 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.
=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
= 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
Function Procedures:
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.
= While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While
= 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
=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.
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.
Property Value
WindowState:
=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
TextBox1.ReadOnly = True
End Sub
=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.
Ans:
End Sub
Ans:
Gets or sets a value specifying if the control should be automatically resized to display all
its contents.
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
=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.
4.Middl right :Vertically aligned at the middle,and horizontally aligned on the right.
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.
Combobox1.Items.Clear()
End Sub
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
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 53
Harish Kanchan II BCA C# and Dot Net Framework
Trackbar: The Track Bar is a horizontal slider that enables the user to select values on
a bar by moving the slider. The tick marks are spaced at regular intervals called the tick
frequency. The user can set the Maximum and Minimum values on the TrackBar, it is also
called as Slide Control.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 54
Harish Kanchan II BCA C# and Dot Net Framework
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
Me.HScrollBar1.Minimum = 0
Me.HScrollBar1.Maximum = 100
Me.HScrollBar1.Value = 35
End Sub
End Class
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.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 55
Harish Kanchan II BCA C# and Dot Net Framework
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 56
Harish Kanchan II BCA C# and Dot Net Framework
2.Explain decision making with if..else if..else statement in VB.NET with syntax and
example
Ans:
Syntqx:
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If
If the Boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Example:
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
' check the boolean condition '
If (a = 10) Then
' if condition is true then print the following '
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
'if else if condition is true '
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
'if else if condition is true
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.
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
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
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 59
Harish Kanchan II BCA C# and Dot Net Framework
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
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
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
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 62
Harish Kanchan II BCA C# and Dot Net Framework
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
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:
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:
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.
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.
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.
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.
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
Addition(x, y)
Here we call the Addition procedure and pass two parameters to it. These parameters are
two Integer values.
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
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.
[ 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.
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
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
= 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.
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()
End Function
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 72
Harish Kanchan II BCA C# and Dot Net Framework
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
17.Explain the procedure for creating the text box in code with example code.
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.
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 Form1()
{
InitializeComponent();
}
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 74
Harish Kanchan II BCA C# and Dot Net Framework
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
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
End Sub
Or else Text property is used to Get or set the Caption to Button control.
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
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
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.
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.
Gets or sets the change in value that one click of the mouse
LargeChange
outside of the slider makes.
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
Controls whether the line down the middle of the control where
ShowSlideArea
the slider rides is drawn. The default value is true.
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:
To remove an item
Remove has one argument that specifies the item to remove.RemoveAt removes the item with
the specified index number.
Call the Clear method to remove all items from the collection:
ComboBox1.Items.Clear();
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
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.
13. RightToLeftChanged Occurs when the value of the RightToLeft property 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.
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.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 84
Harish Kanchan II BCA C# and Dot Net Framework
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:
• DataPager Control
• Repeater Control
• Chart Control
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
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.
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.
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.
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
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:
These are the controls used for validating the data entered in an input control. These
controls belong to the BaseValidator class.
• 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.
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.
The FormView Control displays only a single record in a table at a time retrieved from
a datasource.
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
DeleteItem,ExtractItemvalue,Sort – methods
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
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
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.
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.
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
DIM ds AS DATASET
ds = NEW DATASET()
Adp.Fill(ds,”student”)
DATAGRIDVIEW1.DATAMEMBER = “student”
DATAGRIDVIEW1.DATASOURCE = ds
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.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 92
Harish Kanchan II BCA C# and Dot Net Framework
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 93
Harish Kanchan II BCA C# and Dot Net Framework
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
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 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:
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 96
Harish Kanchan II BCA C# and Dot Net Framework
Property Description
Output:
Property Description
ValidationExpressi Specifies the expression used to validate input control. The
on expression
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 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
Output:
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
Output:
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
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
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
Rows – Obtains a collection of GridViewRow objects that represents the data rows in
a GridView control.
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.
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
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.
Dept of Computer Science Dr.BB Hegde First Grade College Kundapur Page 101