Dr. S.H. Abbas - Learn .Net With Programming (3 in 1) - Covers .NET Using C#, Visual Basic
Dr. S.H. Abbas - Learn .Net With Programming (3 in 1) - Covers .NET Using C#, Visual Basic
NET WITH
PROGRAMMING
( 3-in-1 )
Covers .NET using C#, Visual Basic
ASP.NET
SHRIHIND PUBLICATIONS
SHRIHIND PUBLICATIONS
Registered Office
310, 3rd Floor, Patidar Tower, Freeganj
Ujjain (M.P.) 456010
Phone No. 0734 3554812
Corporate Office
310, 3rd Floor, Patidar Tower, Freeganj
Ujjain (M.P.) 456010
Distribution Center
Ahmedabad, Hyderabad, Bengaluru, Pune, Jabalpur,
Badodara, Bhopal, Indore, Chennai, Kolkata, Mumbai.
website : www.shrihindpublications.com
Email: [email protected]
Copyright Dr. S.H.Abbas
Er. Rahul Ranjan
1st Edition published in English as Learn .Net With
Programming by Dr. S.H.Abbas and Er. Rahul Ranjan
Out in the year 2022 by SHRIHIND PUBLICATIONS.
ISBN - 978-93-92759-74-1
Printed & Bound in India
All rights reserved. No part of this publication may be
reproduced in any form or by any means without the prior
written permission of the publishers
ABOUT PUBLISHER
1
Chapter 4: Covers Windows and Website Development.
ASP.NET is the successor to “classic” ASP technology, the
world’s leading web development tool. ASP.NET solves
many of the problems associated with ASP and provides
an integrated and consistent approach to software
development that builds on the libraries and languages
of the .NET platform.
By the end of the book, you will have built five solid
projects using all the tools and support provided by the
.NET Core 2.0 framework.
Authors
2
CONTENTS
INTRODUCTION TO .NET FRAMEWORK
1.1 Common Language Runtime (CLR) .............................. 9
1.2 .NET Components............................................................... 13
1.3 .Net Framework Design Principle ............................... 17
1.4 Features of .NET Framework ........................................ 20
1.5 Architecture of .NET Framework ................................ 25
1.6 Garbage collection ............................................................. 31
C# BASICS
2.1 What is C#? ........................................................................... 33
2.1.1 Why Use C#? ................................................................ 33
2.1.2 C# Install ....................................................................... 34
2.2 Example: explained ........................................................... 38
2.3 writeline or Write .............................................................. 39
2.4 C# Comments...................................................................... 40
2.4.1 Single-line Comments .............................................. 40
2.4.2 C# Multi-line Comments ......................................... 41
2.5 C# Variables ......................................................................... 41
2.6 Constants ............................................................................... 43
2.7 Declare Many Variables ................................................... 44
2.8 C# Identifiers ....................................................................... 45
3
2.9 C# Data Types ...................................................................... 46
2.10 C# Type Casting ............................................................... 50
2.11 Type Conversion Methods ........................................... 52
2.12 C# Operators ..................................................................... 55
2.13 C# Conditions and If Statements ............................... 64
2.13.1 The if Statement....................................................... 65
2.13.2 The else Statement ................................................ 66
2.13.3 The else if Statement ............................................. 67
2.14 Loops .................................................................................... 72
2.14.1 C# While Loop .......................................................... 72
2.14.2 The Do/While Loop ................................................ 73
2.14.3 C# For Loop ............................................................... 74
2.14.4 The foreach Loop .................................................... 75
2.15 C# Break .............................................................................. 76
2.16 C# Continue ....................................................................... 77
2.17 Break and Continue in While Loop .......................... 77
2.18 C# Arrays ............................................................................ 78
2.18.1 Loop Through an Array ........................................ 80
2.19 C# Methods ........................................................................ 83
2.20 Parameters and Arguments ........................................ 85
2.21 Method Overloading ....................................................... 89
2.22 C# - What is OOP?............................................................ 91
2.22 Access Modifiers ........................................................... 100
4
2.23 Properties and Encapsulation ................................. 102
2.24 Inheritance (Derived and Base Class) .................. 104
2.25 Abstract Classes and Methods................................. 106
2.26 Interfaces ......................................................................... 108
5
4.1.1 C# Hello World ........................................................ 167
4.1.2 Adding Controls to a form ................................... 175
4.1.3 Group Box .................................................................. 175
4.1.4 Label Control ............................................................ 178
4.1.5 Textbox ....................................................................... 181
4.1.6 List box ........................................................................ 183
4.1.7 radiobutton ............................................................... 185
4.1.8 Checkbox .................................................................... 188
4.1.9 Button .......................................................................... 190
4.2 C# Event Handling for Controls ................................ 192
4.3 Tree and picturebox Control ...................................... 197
4.3.1 picturebox Control ................................................. 201
4.4 Web Services ..................................................................... 203
4.5 ADO.NET Architecture .................................................. 204
4.5.1 C# Database Connection: How to connect SQL
Server (Example:) .............................................................. 208
4.6 SQL Command in c# ....................................................... 210
4.7 Distributed Applications .............................................. 250
4.7.1 Evolution of Distributed Applications............ 251
4.8 What is Globalization?................................................... 254
4.9 Authentication in ASP.NET.......................................... 258
6
PROGRAMS/PROJECTS
PROGRAM 1 .............................................................................. 274
PROGRAM 2 .............................................................................. 277
PROGRAM 3 .............................................................................. 279
PROGRAM 4 .............................................................................. 281
PROGRAM 5 .............................................................................. 283
PROGRAM 6 .............................................................................. 286
PROGRAM 7 .............................................................................. 292
PROGRAM 8 .............................................................................. 295
PROGRAM 9 .............................................................................. 298
PROGRAM 10 ............................................................................ 309
PROGRAM 11 ............................................................................ 312
PROGRAM 12 ............................................................................ 317
PROGRAM 13 ............................................................................ 330
7
CHAPTER 1
INTRODUCTION TO .NET
FRAMEWORK
.NET is a software framework which is designed and
developed by Microsoft. The first version of the .Net
framework was 1.0 which came in the year 2002. In easy
words, it is a virtual machine for compiling and executing
programs written in different languages like C#, VB.Net
etc. It is used to develop Form-based applications, Web-
based applications, and Web services. There is a variety
of programming languages available on the .Net platform,
VB.Net and C# being the most common ones. It is used to
build applications for Windows, phone, web, etc. It
provides a lot of functionalities and also supports
industry standards..NET Framework supports more than
60 programming languages in which 11 programming
languages are designed and developed by Microsoft. The
remaining Non-Microsoft Languages which are
supported by .NET Framework but not designed and
developed by Microsoft.
9
remoting, thread management, type-safety, memory
management, robustness, etc. Basically, it is responsible
for managing the execution of .NET programs regardless
of any .NET programming language. It also helps in the
management of code, as code that targets the runtime is
known as the Managed Code and code doesn’t target to
runtime is known as Unmanaged code. Framework Class
Library(FCL): It is the collection of reusable, object-
oriented class libraries and methods, etc that can be
integrated with CLR. Also called the Assemblies. It is just
like the header files in C/C++ and packages in the java.
Installing .NET framework basically is the installation of
CLR and FCL into the system. Below is the overview of
.NET Framework.
10
Figure 1.1 Framework
11
Figure 1.2. .Net Architecture
12
1.2 .NET Components
13
The database connection is no longer required. If
the application has finished all operations on a
database, then the database connection may no
longer be required.
14
1. Class Library
16
1.3 .Net Framework Design Principle
• Choosing a compiler
• Compiling your code to MSIL
• Compiling MSIL to native code
• Running code
18
Figure 1.3 FCL
Choosing a Compiler
19
code references, and other data that the runtime
uses at execution time.
• The runtime locates and extracts the metadata
from the file as well as from framework class
libraries (FCL) as needed during execution.
Running Code
21
• Event driven programming is a paradigm in which
the flow of the program is determined by events
(mouse clicks, key presses), sensor outputs, or
messages from other programs/threads.
Manifest:
System Namespaces:
23
without using classes from the .net system
namespace.
• The .net framework class library consists of several
thousand classes and other types, (such as
interfaces, structures and enumerations) that are
divided into several namespaces
System.Data:
System.IO:
System.windows.forms:
25
Microsoft .NET (pronounced “dot net”) is a software
component that runs on the Windows operating
system...NET provides tools and libraries that enable
developers to create Windows software much faster and
easier.The .NET Framework must be installed on a user’s
PC to run .NET applications
.Net Framework
26
Following is the .NET framework Stack that shows the
modules and components of the Framework.
27
Figure 1.3: Architecture of .NET Framework
28
Figure 1.4 FCL (Framework Class Library)
Winforms
29
common application tasks such as reading and writing to
the file system.
ASP.NET
ADO.NET
Entity Framework
31
• An allocation is made any time you declare an
object with a “new” keyword or a value type is
boxed. Allocations are typically very fast.
32
CHAPTER 2
C# BASICS
2.1 What is C#?
C# is pronounced "C-Sharp".
C# is used for:
• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
2.1.2 C# Install
34
Then click on the "Install more tools and features"
button:
35
Choose "Console App (.NET Core)" from the list and click
on the Next button:
36
Visual Studio will automatically generate some code for
your project:
Program.cs
Using System;
Namespace helloworld
{
Class Program
{
Static void Main(string[] args)
{
Console.writeline("Hello World!");
}
}
}
37
2.2 Example: explained
38
Line 7: Another thing that always appear in a C#
program, is the Main method. Any code inside its curly
brackets {} will be executed. You don't have to
understand the keywords before and after Main. You will
get to know them bit by bit while reading this tutorial.
Note: Unlike Java, the name of the C# file does not have
to match the class name, but they often do (for better
organization). When saving the file, save it using a proper
name and add ".cs" to the end of the filename. To run the
Example: above on your computer, make sure that C# is
properly installed
Example:
Console.writeline("Hello World!");
Result:
2.4 C# Comments
40
Any text between // and the end of the line is ignored by
C# (will not be executed).
Example::
// This is a comment
Console.writeline("Hello World!");
Example::
Console.writeline("Hello World!");
2.5 C# Variables
Syntax
Example::
42
String name = "John";
Console.writeline(name);
Example::
Console.writeline(mynum);
2.6 Constants
Example::
43
Note: You cannot declare a constant variable without
assigning the value. If you do, an error will occur: A const
field requires a value to be provided.
Example::
Console.writeline(fullname);
Example::
Int x = 5;
Int y = 6;
Example::
Int x = 5, y = 6, z = 50;
44
Console.writeline(x + y + z);
Example::
Int x, y, z;
X = y = z = 50;
Console.writeline(x + y + z);
2.8 C# Identifiers
Example::
// Good
Int m = 60;
45
2.9 C# Data Types
Example::
46
Numbers
Integer Types
Int
Example::
Console.writeline(mynum);
Long
Console.writeline(mynum);
Float
Example::
Console.writeline(mynum);
Double
Example::
Console.writeline(mynum);
48
Scientific Numbers
Example::
Float f1 = 35e3f;
Double d1 = 12E4D;
Console.writeline(f1);
Console.writeline(d1);
Booleans
Example::
Characters
49
The char data type is used to store a single character. The
character must be surrounded by single quotes, like 'A'
or 'c':
Example::
Console.writeline(mygrade);
Strings
Example::
Console.writeline(greeting);
50
Explicit Casting (manually) - converting a larger type to
a smaller size type
Implicit Casting
Example::
Int myint = 9;
Console.writeline(myint); // Outputs 9
Console.writeline(mydouble); // Outputs 9
Explicit Casting
Example::
51
Console.writeline(mydouble); // Outputs 9.78
Console.writeline(myint); // Outputs 9
Example::
Console.writeline(Convert.tostring(myint)); // convert
int to string
Console.writeline(Convert.todouble(myint)); //
convert int to double
Console.writeline(Convert.toint32(mydouble)); //
convert double to int
Console.writeline(Convert.tostring(mybool)); //
convert bool to string
52
You have already learned that Console.writeline() is used
to output (print) values. Now we will use
Console.readline() to get user input.
Example::
Console.writeline("Enter username:");
53
User Input and Numbers
Example::
54
2.12 C# Operators
Example::
Arithmetic Operators
C# Assignment Operators
55
Example::
Int x = 10;
Example::
Int x = 10;
X += 5;
C# Comparison Operators
56
Comparison operators are used to compare two values:
C# Logical Operators
Math.Max(x,y)
Example::
57
Math.Max(5, 10);
Math.Min(x,y)
Example::
Math.Min(5, 10);
Math.Sqrt(x)
Example::
Math.Sqrt(64);
Math.Abs(x)
Example::
Math.Abs(-4.7);
Math.Round()
Example::
58
Math.Round(9.99);
C# Strings
Example::
String Length
Example::
Other Methods
59
Example::
String Concatenation
Example::
Console.writeline(name);
String Interpolation
Example:
Console.writeline(name);
Example:
WARNING!
Example:
Int x = 10;
61
Int y = 20;
C# Booleans
YES / NO
ON / OFF
TRUE / FALSE
For this, C# has a bool data type, which can take the
values true or false.
Boolean Values
62
A boolean type is declared with the bool keyword and
can only take the values true or false:
Example:
Boolean Expression
Example:
Int x = 10;
Int y = 9;
63
2.13 C# Conditions and If Statements
64
• Use else if to specify a new condition to test, if the
first condition is false
• Use switch to specify many alternative blocks of
code to be executed
Syntax
If (condition)
65
2.13.2 The else Statement
Syntax
If (condition)
}
66
Else
Example: explained
Syntax
If (condition1)
67
{
Else if (condition2)
Else
68
Example: explained
C# Switch Statements
Syntax
Switch(expression)
Case x:
// code block
Break;
Case y:
// code block
Break;
69
Default:
// code block
Break;
Using System;
Namespace myapplication
Class Program
Int day = 4;
Switch (day)
Case 1:
Console.writeline("Monday");
Break;
70
Case 2:
Console.writeline("Tuesday");
Break;
Case 3:
Console.writeline("Wednesday");
Break;
Case 4:
Console.writeline("Thursday");
Break;
Case 5:
Console.writeline("Friday");
Break;
Case 6:
Console.writeline("Saturday");
Break;
Case 7:
Console.writeline("Sunday");
Break;
71
}
2.14 Loops
Syntax
72
While (condition)
In the Example: below, the code in the loop will run, over
and over again, as long as a variable (i) is less than 5:
Syntax
Do
{
73
// code block to be executed
While (condition);
Syntax
74
Statement 1 is executed (one time) before the execution
of the code block.
Syntax
75
The following Example: outputs all elements in the cars
array, using a foreach loop:
2.15 C# Break
76
2.16 C# Continue
Continue Example:
77
2.18 C# Arrays
Create an Array
String[] cars;
78
Int[] mynum = {10, 20, 30, 40};
Example:
Example:
Cars[0] = "Opel";
Example:
Cars[0] = "Opel";
Console.writeline(cars[0]);
79
Array Length
Example:
Console.writeline(cars.Length);
// Outputs 4
You can loop through the array elements with the for
loop, and use the Length property to specify how many
times the loop should run.
Example:
Console.writeline(cars[i]);
Sort Arrays
80
There are many array methods available, for Example:
Sort(), which sorts an array alphabetically or in an
ascending order:
Example:
// Sort a string
Array.Sort(cars);
Console.writeline(i);
// Sort an int
Array.Sort(mynumbers);
Console.writeline(i);
System.Linq Namespace
81
Other useful array methods, such as Min, Max, and Sum,
can be found in the System.Linq namespace:
Example:
Using System;
Using System.Linq;
Namespace myapplication
Class Program
}
82
}
2.19 C# Methods
Create a Method
Example:
Class Program
// code to be executed
83
}
Call a Method
Example:
Mymethod();
84
2.20 Parameters and Arguments
Example:
Mymethod("Liam");
Mymethod("Jenny");
Mymethod("Anja");
85
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Example:
Console.writeline(country);
Mymethod("Sweden");
Mymethod("India");
Mymethod();
86
Mymethod("USA");
// Sweden
// India
// Norway
// USA
Multiple Parameters
Example:
Mymethod("Liam", 5);
Mymethod("Jenny", 8);
Mymethod("Anja", 31);
87
}
// Liam is 5
// Jenny is 8
// Anja is 31
Return Values
Example:
Return 5 + x;
Console.writeline(mymethod(3));
// Outputs 8 (5 + 3)
88
Named Arguments
Example:
Example:
89
Int mymethod(int x)
Float mymethod(float x)
Example:
Return x + y;
Return x + y;
Create a Class
Class Car
Create an Object
92
Example:
Class Car
Console.writeline(myobj.color);
Multiple Objects
Example:
Class Car
{
93
String color = "red";
Console.writeline(myobj1.color);
Console.writeline(myobj2.color);
Prog2.cs
Prog.cs
Prog2.cs
Class Car
94
{
Class Members
Example:
// The class
Class myclass
// Class members
95
}
Class Car
String color;
Int maxspeed;
Myobj.color = "red";
Myobj.maxspeed = 200;
Console.writeline(myobj.color);
Console.writeline(myobj.maxspeed);
Object Methods
Example:
Class Car
Constructors
97
A constructor is a special method that is used to initialize
objects. The advantage of a constructor, is that it is called
when an object of a class is created. It can be used to set
initial values for fields:
Example:
Create a constructor:
Class Car
Public Car()
98
Console.writeline(Ford.model); // Print the value of
model
// Outputs "Mustang"
Constructor Parameters
Example:
Class Car
99
{
Model = modelname;
Console.writeline(Ford.model);
// Outputs "Mustang"
Private Modifier
Class Car
Console.writeline(myobj.model);
Mustang
Public Modifier
Example:
Class Car
Class Program
Console.writeline(myobj.model);
Mustang
Example:
Class Person
103
2.24 Inheritance (Derived and Base Class)
104
have their own implementation of an animal sound (the
pig oinks, and the cat meows, etc.):
Example:
{
105
Public void animalsound()
// Abstract class
// Regular method
Console.writeline("Zzz");
107
Class Program
2.26 Interfaces
Example:
// interface
Interface Animal
Multiple Interfaces
Example:
Interface ifirstinterface
Interface isecondinterface
{
109
Console.writeline("Some text..");
Class Program
Myobj.mymethod();
Myobj.myothermethod();
C# Enums
Example:
Enum Level
Low,
Medium,
High
Example:
Class Program
Enum Level
Low,
Medium,
High
111
}
Console.writeline(myvar);
Medium
112
CHAPTER 3
C# - Stream
113
Bufferedstream: bufferedstream reads or writes bytes
from other Streams to improve certain I/O operations'
performance.
114
read strings (characters) from different Streams like
filestream, memorystream, etc.
115
3.2 C# - Multithreading
116
The Unstarted State − It is the situation when the
instance of the thread is created but the Start method is
not called.
Using System;
Using System.Threading;
Namespace multithreadingapplication {
Class mainthreadprogram {
Thread th = Thread.currentthread;
Th.Name = "mainthread";
Console.readkey();
This is mainthread
118
3.4 Creating Threads
Using System;
Using System.Threading;
Namespace multithreadingapplication {
Class threadcreationprogram {
Childthread.Start();
Console.readkey();
119
}
Contents
Console.openstandardinput Method()
Console.openstandardoutput Method()
Console.Read Method()
Console.readline Method()
120
Console.Write Method(Boolean)
Console.Write Method(String)
/* Console Input/Ouput */
Using System;
121
Class consoletest
Console.Write("Hello");
Console.writeline("World");
Console.Write("Hello, ");
Console.Write(name);
Console.writeline(" ! ");
122
Data from the console is read from the standard input
stream; normal data to the console is written to the
standard output stream; and error data to the console is
written to the standard error output stream. These
streams are automatically associated with the console
when your application start, and are presented to you as
the In, Out, and Error properties.
Console.openstandardinput Method()
123
Public static void Main()
Console.writeline("Decoded String:");
Console.writeline(new string(chars));
Console.openstandardoutput Method()
If (args.Length < 2)
Console.writeline(usagetextt);
Return 1;
Try
Console.setout(writer);
Console.setin(new streamreader(args[0]));
}
125
Catch(ioexception e)
Errorwriter.writeline(e.Message);
Errorwriter.writeline(usagetext);
Return 1;
String line;
String newline =
line.Replace(("").padright(tabsize,'),"\t");
Console.writeline(newline);
Writer.Close();
126
Standardoutput.autoflush = true;
Console.setout(standardoutput);
Return 0;
Console.Read Method()
Int i;
Char c;
While(true)
I = Console.Read();
127
If (i == 1)
Break;
C = (char) l;
Console.writeline("Echo: )0)",c);
Console.writeline("Done");
Return 0;
Console.readline Method()
128
Public static int Main(String[] args)
If (args.Length < 2)
Console.writeline(usagetextt);
Return 1;
Try
Console.setout(writer);
Console.setin(new streamreader(args[0]));
Catch(ioexception e)
Errorwriter.writeline(e.Message);
129
Errorwriter.writeline(usagetext);
Return 1;
String line;
String newline =
line.Replace(("").padright(tabsize,'),"\t");
Console.writeline(newline);
Writer.Close();
Standardoutput.autoflush = true;
Console.setout(standardoutput);
130
Return 0;
Console.Write Method(Boolean)
String lineinput;
If (isfirstfield)
131
Isfirstfield = false;
Else
Console.Write(',');
Try
{
Console.Write(Convert.tobyte(Convert.toboolean(item)))
;
Catch(formatexception)
Console.Write(item);
Console.writeline();
Console.Write Method(String)
132
This method writes the specified string value to the
standard output stream. If value is a null reference,
nothing is written to the standard output stream.
Consider the following code for illustration.
String lineinput;
If (isfirstfield)
Isfirstfield = false;
Else
Console.Write(',');
133
Try
{
Console.Write(Convert.tobyte(Convert.toboolean(item)))
;
Catch(formatexception)
Console.Write(item);
Console.writeline();
1. Private Assembly
2. Shared Assembly
1. Private Assembly
2. Shared Assembly
C:\Windows\Microsoft.NET\Framework\v4.0.30319.
( Start > Programs > Microsoft Visual Studio .NET 2005 >
Visual Studio .NET Tools > Visual Studio .NET 2005
Command Prompt )
136
C:\Projects\myapplication\Infragistics4.webui.ultraweb
chart.v21.2.dll
What is global.asax
Ispostback
How to ?
Create-global
<script runat="server">
139
Void Session_End(object sender, eventargs e)
</script>
140
page is posted to the server. If a user enters information
into a web application, that information would be lost in
the round trip from the browser (MSDN).
Session["username"] = txtname.Text;
Response.Redirect("Home.aspx");
Session Event
Session["master"] = "~/Master.master";
Session_End
Response.Write("Session_End");
Inprocmode
142
State Server Mode
Custom Mode
Application
Application_Start
143
}
Application_Error
Application_ End
Cache
Response.Cache.setexpirestime(datetime.Now.adddays(1
));
144
Client Side
3.9 Cookie
Persistence
Response.Cookies["cookiename"].Expires =
datetime.Today.addhours(1);
Non-Persistence
145
Response.Cookies["cookiename"].Value = "Test Cookies";
Control state
If (!Ispostback)
If (hiddenfield1.Value != null)
146
{
Hiddenfield1.Value = val.tostring();
Label1.Text = val.tostring();
Viewstate
Example: 1 - Count.
If (ispostback)
If (viewstate["count"] != null)
147
{
Int viewstateval =
Convert.toint32(viewstate["count"]) + 1;
Lblcount.Text = viewstateval.tostring();
Viewstate["count"] = viewstateval.tostring();
Else
Viewstate["count"] = "1";
Lblcount.Text = viewstate["count"].tostring();
If (viewstate["username"] != null)
Lblname.Text = viewstate["username"].tostring();
OR,
148
Viewstate["username"] = txtusername.Text;
Hidden Fields
Hiddenfield Control
149
In HTML pages, you might use something such as the
following code snippet to implement a hidden field:
Value="/wepdwujl0chlbr...yfl+BDX7xhMw=" />
Codefile="hiddenfielddemo.aspx.cs"
Inherits="hiddenfielddemo" %>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
151
<body>
Function changehiddenvalue()
Alert("Entering changehiddenvalue");
Var txt =
document.getelementbyid("txtsecretvalue");
Hdn.value = txt.value;
Alert("Value changed");
</script>
<div>
Onvaluechanged="hdnsecretvalue_valuechanged"
/>
152
<asp:textbox ID="txtsecretvalue" runat="server" />
<br />
<br />
Onclick="changehiddenvalue()" />
<br />
<br />
</div>
</form>
</body>
</html>
When the user requests for the web page again, browser
looks on the hard drive for the cookie associated with the
web page. Browser stores separate cookie for each
different sites user visited.
Cookies collection
httpcookie
Httpcookie Example:
155
In the following Example:, we are creating and adding
cookie with the help of httpcookie class.
// cookieExample:.aspx
Code
// cookieExample:.aspx.cs
1. Using System;
2. Using System.Web;
3. Namespace webformscontrolls
4. {
156
5. Public partial class cookieExample: :
System.Web.UI.Page
6. {
7. Protected void Page_Load(object sender, eventargs
e)
8. {
9. //-------------- Creating Cookie --------------------------
//
10. // Creating httpcookie instance by specifying name
"student"
11. Httpcookie cokie = new httpcookie("student");
12. // Assigning value to the created cookie
13. Cokie.Value = "Rahul Kumar";
14. // Adding Cookie to the response instance
15. Response.Cookies.Add(cokie);
16. //--------------- Fetching Cookie -------------------------
//
17. Var co_val = Response.Cookies["student"].Value;
18. Label1.Text = co_val;
19. }
20. }
21. }
// Default.aspx
157
1. <%@ Page Title="Home Page" Language="C#"
autoeventwireup="true"
codebehind="Default.aspx.cs"
2. Inherits="coockieExample:._Default" %>
3. <form id="form1" runat="server">
4. <asp:Label ID="Label1" runat="server"
Text="Select Brand Preferences"></asp:Label>
5. <br />
6. <br />
7. <asp:checkbox ID="apple" runat="server"
Text="Apple" />
8. <br />
9. <asp:checkbox ID="dell" runat="server"
Text="Dell" />
10. <br />
11. <asp:checkbox ID="lenevo" runat="server"
Text="Lenevo" />
12. <br />
13. <asp:checkbox ID="acer" runat="server"
Text="Acer" />
14. <br />
15. <asp:checkbox ID="sony" runat="server"
Text="Sony" />
16. <br />
17. <asp:checkbox ID="wipro" runat="server"
Text="Wipro" />
18. <br />
19. <br />
20. <asp:Button ID="Button1" runat="server"
onclick="Button1_Click" Text="Submit" />
158
21. <p>
22. <asp:Label ID="Label2"
runat="server"></asp:Label>
23. </p>
24. </form>
Codebehind
// Default.aspx.cs
1. Using System;
2. Using System.Web.UI;
3. Namespace coockieExample:
4. {
5. Public partial class _Default : Page
6. {
7. Protected void Page_Load(object sender, eventargs
e)
8. {
9. // Setting expiring date and time of the cookies
10. Response.Cookies["computer"].Expires =
datetime.Now.adddays(-1);
11. }
12. Protected void Button1_Click(object sender,
eventargs e)
13. {
14. Label2.Text = "";
15. // --------------- Adding Coockies ---------------------//
16. If (apple.Checked)
17. Response.Cookies["computer"]["apple"] = "apple";
18. If (dell.Checked)
159
1. 19.
Response.Cookies["computer"]["dell"] = "dell";
19. If (lenevo.Checked)
20. Response.Cookies["computer"]["lenevo"] =
"lenevo";
21. If (acer.Checked)
22. Response.Cookies["computer"]["acer"] = "acer";
23. If (sony.Checked)
24. Response.Cookies["computer"]["sony"] = "sony";
25. If (wipro.Checked)
26. Response.Cookies["computer"]["wipro"] =
"wipro";
27. // --------------- Fetching Cookies -----------------------
//
28. If (Request.Cookies["computer"].Values.tostring()
!= null)
29. {
30. If (Request.Cookies["computer"]["apple"] != null)
31. Label2.Text +=
Request.Cookies["computer"]["apple"] + " ";
32. If (Request.Cookies["computer"]["dell"] != null)
33. Label2.Text +=
Request.Cookies["computer"]["dell"] + " ";
34. If (Request.Cookies["computer"]["lenevo"] != null)
35. Label2.Text +=
Request.Cookies["computer"]["lenevo"] + " ";
36. If (Request.Cookies["computer"]["acer"] != null)
37. Label2.Text +=
Request.Cookies["computer"]["acer"] + " ";
38. If (Request.Cookies["computer"]["sony"] != null)
160
39. Label2.Text +=
Request.Cookies["computer"]["sony"] + " ";
40. If (Request.Cookies["computer"]["wipro"] != null)
41. Label2.Text +=
Request.Cookies["computer"]["wipro"] + " ";
42. }else Label2.Text = "Please select your choice";
43. Response.Cookies["computer"].Expires =
datetime.Now.adddays(-1);
44. }
45. }
46. }
Output:
161
3.13 Cross Page Posting In ASP.NET
If (Page.previouspage != null)
163
Step 5: To retrieve values from the source page, you
must access controls using the ‘findcontrol()’ method of
the ‘previouspage’. We will be accessing the Text
property of the Button control placed in Default.aspx.
If (Page.previouspage != null)
Button btn =
(Button)(Page.previouspage.findcontrol("button1"));
Label1.Text = btn.Text;
164
3.14 Web Configuration and Machine
Configuration Files
1. Machine.config
2. Web.config
Machine.Config
Web.Config
165
CHAPTER 4
166
So an Example: of the controls available in the above
application
167
Step 2) The next step is to choose the project type as a
Windows Forms application. Here we also need to
mention the name and location of our project.
168
1. In the project dialog box, we can see various
options for creating different types of projects in
Visual Studio. Click the Windows option on the left-
hand side.
2. When we click the Windows options in the
previous step, we will be able to see an option for
Windows Forms Application. Click this option.
3. We will give a name for the application. In our case,
it is demoapplication. We will also provide a
location to store our application.
4. Finally, we click the ‘OK’ button to let Visual Studio
create our project.
If the above steps are followed, you will get the below
output in Visual Studio.
Output:-
169
You will see a Form Designer displayed in Visual Studio.
It’s in this Form Designer that you will start building
your Windows Forms application.
171
Once you drag the label to the form, you can see the label
embedded on the form as shown below.
172
Step 4) The next step is to go to the properties of the
control and Change the text to ‘Hello World’.
173
If you follow all of the above steps and run your program
in Visual Studio, you will get the following output
Output:-
174
4.1.2 Adding Controls to a form
176
Once you make the above changes, you will see the
following output
Output:-
177
In the output, you can clearly see that the Groupbox was
added to the form. You can also see that the text of the
groupbox was changed to “User Details.”
178
Step 2) Once the label has been added, go to the
properties window by clicking on the label control. In the
properties window, go to the Text property of each label
control.
179
Once you make the above changes, you will see the
following output
Output:-
180
You can see the label controls added to the form.
4.1.5 Textbox
181
Step 2) Once the text boxes have been added, go to the
properties window by clicking on the textbox control. In
the properties window, go to the Name property and add
a meaningful name to each textbox. For Example:, name
the textbox for the user as txtname and that for the
address as txtaddress. A naming convention and
standard should be made for controls because it becomes
easier to add extra functionality to these controls, which
we will see later on.
182
In the output, you can clearly see that the Textboxes was
added to the form.
Step 1) The first step is to drag the list box control onto
the Windows Form from the toolbox as shown below
183
Step 2) Once the list box has been added, go to the
properties window by clicking on the list box control.
184
box. In our case, we have selected items
“collection”.
3. In the String Collection Editor, which pops up,
enter the city names. In our case, we have entered
“Mumbai”, “Bangalore” and “Hyderabad”.
4. Finally, click on the ‘OK’ button.
Once you make the above changes, you will see the
following output
Output:
4.1.7 radiobutton
185
Step 1) The first step is to drag the ‘radiobutton’ control
onto the Windows Form from the toolbox as shown
below.
186
1. First, you need to change the text property of both
Radio controls. Go the properties windows and
change the text to a male of one radiobutton and
the text of the other to female.
One you make the above changes, you will see the
following output
Output:-
187
4.1.8 Checkbox
188
Step 2) Once the checkbox has been added, go to the
properties window by clicking on the Checkbox control.
Once you make the above changes, you will see the
following output
189
Output:-
4.1.9 Button
190
Step 2) Once the Button has been added, go to the
properties window by clicking on the Button control.
Once you make the above changes, you will see the
following output
191
Output:-
192
Let’s take a look at one of the event and how it can be
handled before we go to the button event scenario.
193
1. This is the event handler method which is
automatically created by Visual Studio when you
double-click the List box control. You don’t need to
worry about the complexity of the method name or
the parameters passed to the method.
One you make the above changes, and run the program in
Visual Studio you will see the following output
Output:-
194
From the output, you can see that when any item from
the list box is selected, a message box will pops up. This
will show the selected item from the listbox.
195
3. Finally, we use the messagebox method to display
the name and address values to the user.
One you make the above changes, and run the program in
Visual Studio you will see the following output
Output:-
196
4.3 Tree and picturebox Control
Tree Control
Step 1) The first step is to drag the Tree control onto the
Windows Form from the toolbox as shown below
197
Step 2) The next step is to start adding nodes to the tree
collection so that it can come up in the tree accordingly.
First, let’s follow the below sub-steps to add a root node
to the tree collection.
198
1. Go to the properties toolbox for the tree view
control. Click on the Node’s property. This will
bring up the treenode Editor
199
1. First, click on the Add child button. This will allow
you to add child nodes to the Tree collection.
2. For each child node, change the text property. Keep
on repeating the previous step and this step and
add 2 additional nodes. In the end, you will have 3
nodes as shown above, with the text as Label,
Button, and Checkbox respectively.
3. Click on the OK button
Once you have made the above changes, you will see the
following output.
Output:-
200
You will be able to see the Tree view added to the form.
When you run the Windows form application, you can
expand the root node and see the child nodes in the list.
201
Step 2) The next step is to actually attach an image to the
picture box control. This can be done by following the
below steps.
One you make the above changes, you will see the
following output
Output:-
202
From the output, you can see that an image is displayed
on the form.
What is ADO.NET?
204
The architecture of ADO.NET:
1. Connection
2. Command
3. Datareader
4. Dataadapter
5. Dataset
6. Dataview
205
Let us understand each of the components in detail.
Connection:
Datareader:
Dataset:
Dataadapter:
Dataview Class
207
A dataview enables you to create different views of the
data stored in a datatable, a capability that is often used
in data-binding applications. Using a dataview, you can
expose the data in a table with different sort orders, and
you can filter the data by row state or based on a filter
expression.
208
Edition, which is a free database software provided by
Microsoft.
209
1. Selecting data from the database – Once the
connection has been established, the next
important aspect is to fetch the data from the
database. C# can execute ‘SQL’ select command
against the database. The ‘SQL’ statement can be
used to fetch data from a specific table in the
database.
• Username – sa
• Password – demo123
211
Step 2) The next step is to choose the project type as a
Windows Forms application. Here, we also need to
mention the name and location of our project.
212
• In the project dialog box, we can see various
options for creating different types of projects in
Visual Studio. Click the Windows option on the left-
hand side.
213
Step 4) Now double click the form so that an event
handler is added to the code for the button click event. In
the event handler, add the below code.
Using System;
Using System.Collections.Generic;
Using System.componentmodel;
Using System.Data;
Using System.Data.sqlclient;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Using System.Windows.Forms;
Namespace demoapplication1
{
Public partial class Form1 : Form
{
Public Form1()
{
214
Initializecomponent();
}
Code Explanation:-
Output:-
216
When you click on “connect” button, from the output, you
can see that the database connection was established.
Hence, the message box was displayed.
217
TutorialID TutorialName
1 C#
2 ASP.Net
218
Code Explanation:-
219
• The next step is to define the SQL statement, which
will be used against our database. In our case, it is
“Select tutorialid, tutorialname from demotb”. This
will fetch all the rows from the table demotb.
• Now that we have all the rows of the table with us,
we need a mechanism to access the row one by
one. For this, we will use the while statement. The
while statement will be used to access the rows
from the data reader one at a time. We then use the
getvalue method to get the value of tutorialid and
tutorialname.
220
Code Explanation:-
When the above code is set, and the project is run using
Visual Studio, you will get the below output. Once the
form is displayed, click the Connect button.
Output:-
From the output, you can clearly see that the program
was able to get the values from the database. The data is
then displayed in the message box.
221
Just like Accessing data, C# has the ability to insert
records into the database as well. To showcase how to
insert records into our database, let’s take the same table
structure which was used above.
TutorialID TutorialName
1 C#
2 ASP.Net
TutorialID TutorialName
3 VB.Net
222
Code Explanation:-
223
• Next, we create the command object which is used
to execute the SQL statement against the database.
In the SQL command, you have to pass the
connection object and the SQL string
Output:-
224
If you go to SQL Server Express and see the rows in the
demotb table, you will see the row inserted as shown
below
C# Update Database
225
TutorialID TutorialName
1 C#
2 ASP.Net
3 VB.Net
Old Row
TutorialID TutorialName
3 VB.Net
New row
TutorialID TutorialName
3 VB.Net Complete
226
So let’s add the following code to our program. The
below code snippet will be used to update an existing
record in our database.
227
• The next step is to define the SQL statement which
will be used against our database. In our case we
are issuing an update statement, this will update
the Tutorial name to “VB.Net Complete” while the
tutorialid is unchanged and kept as 3.
Output:-
228
If you actually go to SQL Server Express and see the rows
in the demotb table, you will see the row was
successfully updated as shown below.
229
Deleting Records
TutorialID TutorialName
1 C#
2 ASP.Net
3 VB.Net Complete
TutorialID TutorialName
3 VB.Net Complete
230
Code Explanation:-
Output:-
231
If you actually go to SQL Server Express and see the rows
in the demotb table, you will see the row was
successfully deleted as shown below.
232
In the earlier sections, we have seen how to we can use
C# commands such as sqlcommand and sqlreader to
fetch data from a database. We also saw how we read
each row of the table and use a messagebox to display
the contents of a table to the user.
TutorialID TutorialName
1 C#
2 ASP.Net
3 VB.Net Complete
233
What this means is that C# can automatically populate
the value of the textbox as per a particular field of the
table.
Visual Studio will ensure that it writes the code for you to
ensure the linkage works. Then when you run your
application, the textbox controls will automatically
connect to the database, fetch the data and display it in
the textbox controls. No coding is required from the
developer’s end to achieve this.
234
• Put the text value of the first label as tutorialid
• Put the text value of the second label as
tutorialname
• Put the name property of the first textbox as txtid
• Put the name property of the second textbox as
txtname
Below is the how the form would look like once the
above-mentioned steps are performed.
235
Step 3) The next step is to add a binding to our database.
This can be done by going to any of the Textbox control
and clicking on the databindings->Text property. The
Binding Navigator is used to establish a link from your
application to a database.
The following screen will show up. Click on the link- “Add
Project Data Source”. When you click on the project data
source, you will be presented with a wizard; this will
allow you to define the database connection.
236
Step 4) Once you click on the Add Project Data Source
link, you will be presented with a wizard which will be
used to create a connection to the demotb database. The
following steps show in detail what needs to be
configured during each step of the wizard.
237
the parameters such as server name, database
name, and the name of the driver.
238
• In this screen, we will confirm all the settings
which were carried on the previous screens.
239
• In the next screen, click on the “Next” button to
confirm the creation of the connection string
240
• In this step,
• Choose the tables of Demotb, which will be shown
in the next screen.
• This table will now become an available data
source in the C# project
241
When you click the Finish button, Visual Studio will now
ensure that the application can query all the rows in the
table Demotb.
For the first text box choose the Tutorial ID. Repeat this
step for the second textbox and choose the field as
tutorialname. The below steps shows how we can
navigate to each control and change the binding
accordingly.
242
• Click on the Tutorial ID control.
243
• When you click the down arrow button, you will
see the demotbbinding Source option. And under
this, you will see the options of tutorialname and
tutorialid. Choose the Tutorial ID one.
Repeat the above 3 steps for the Tutorial Name text box.
245
When all of the above steps are executed successfully,
you will get the below-mentioned output.
Output:-
Now when the project is launched, you can see that the
textboxes automatically get the values from the table.
246
When you click the Next button on the Navigator, it
automatically goes to the next record in the table. And
the values of the next record automatically come in the
text boxes
C# datagridview
247
Step 2) In the next step, we need to connect our data grid
to the database. In the last section, we had created a
project data source. Let’s use the same data source in our
Example:.
If all the above steps are executed as shown, you will get
the below-mentioned output.
Output:-
248
From the output, you can see that the grid was populated
by the values from the database.
Summary
249
• The data adapter object is used to perform SQL
operations such as insert, delete, and update
against the database.
• C# can bind controls to the various fields in a table.
They are bound by defining a data source in C#.
The data source is used to pull the data from the
database and populate them in the controls.
• The binding navigator is used to automatically
navigate through the rows in a table.
• The data grid in C# can connect to the database
and display all the values from the table in a grid-
like format.
252
provides an abstraction over the complex network
programming and exposes a simple mechanism for
inter-application domain communication. The key
objectives of .NET remoting are flexibility and
extensibility.
Globalization Examples
If that’s still a bit vague for you, here are a few Example:s
of globalization in the world of business:
255
The rise of globalization also means that there has
arguably never been a better time to build a business
into a global company. There are a huge range of
opportunities available to companies looking to expand,
from access to a global talent pool to an increased
volume of information that can be used to position a
business. As it gets easier to enter new markets, there
are also more product niches to take advantage of—and
new customers to attract.
What is Internationalization?
256
assembly instructions for its furniture by using only
diagrams and illustrations, without including any text
that would need to be translated. Products with
instructions that do require translation are still often
written with the goal of being as culturally-neutral as
possible. This, of course, is easier said than done.
What is Localization?
257
Localization is the process of adapting a product to a
specific target market. This usually happens after
internationalization has taken place. Where
internationalization develops a product that’s easy to
adapt for many audiences in many different countries,
localization takes that product and makes it highly
relevant for one specific market.
259
access, so requests are automatically authenticated, but
you can change this default on a per - application basis
with in IIS.
Authentication Providers
Introduction
261
Step 1: First start Visual Studio 2010 by clicking "File" ->
"New" -> "Web Site..." then click on "ASP.NET Web Site".
Now write the following inline code that will design your
web page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
Width: 40%;
Border-style: solid;
Border-width: 1px;
Background-color:Silver;
Height: 152px;
.style2
262
{
Width: 295px;
.style3
Width: 754px;
</style>
</head>
<body>
<div>
<table class="style1">
<tr>
<td class="style2">
263
</td>
<td class="style3">
Employee_Information</td>
</tr>
<tr>
<td class="style2">
Name:</td>
<td class="style3">
<asp:textbox ID="textbox1"
runat="server"></asp:textbox>
</td>
</tr>
<tr>
<td class="style2">
Emp_Id:</td>
264
<td class="style3">
<asp:textbox
ID="textbox2"runat="server"></asp:textbox>
</td>
</tr>
<tr>
<td class="style2">
Qualification:</td>
<td class="style3">
<asp:dropdownlist ID="dropdownlist1"
runat="server" Height="22px" Width="132px">
<asp:listitem>--SELECT--</asp:listitem>
<asp:listitem>MCA</asp:listitem>
<asp:listitem>BCA</asp:listitem>
<asp:listitem>MBA</asp:listitem>
<asp:listitem>BBA</asp:listitem>
265
<asp:listitem>btech</asp:listitem>
<asp:listitem>mtech</asp:listitem>
</asp:dropdownlist>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3">
</td>
</tr>
</table>
266
<asp:datalist ID="datalist1" runat="server"
backcolor="#DEBA84" bordercolor="#DEBA84"
Style="margin-right: 32px">
<footerstyle backcolor="#F7DFB5"
forecolor="#8C4510"/>
<itemstyle backcolor="#FFF7E7"
forecolor="#8C4510"/>
<itemtemplate>
<hrsize=0 />
Name:<%#databinder.Eval(Container.dataitem,"name")
%><br/>
267
Emp_id:<%#databinder.Eval(Container.dataitem,"Emp_i
d")%></a><br/>
Qualification:<%#databinder.Eval(Container.dataitem,"Q
ualification")%><br/>
</itemtemplate>
</asp:datalist>
<br />
</div>
</form>
</body>
</html>
Designing.jpg
<?Xml version="1.0"encoding="utf-8"?>
268
<employeeinformation>
</employeeinformation>
Using System.Data;
Using System.Xml;
If (!Ispostback)
Binddatalist();
269
}
Dataset ds = newdataset();
Ds.readxml(xmlreader);
Xmlreader.Close();
If (ds.Tables.Count != 0)
Datalist1.datasource = ds;
Datalist1.databind();
Else
Datalist1.datasource = null;
Datalist1.databind();
}
270
}
Xmldoc.Load(Server.mappath("Employee.xml"));
Binddatalist();
Xmldoc.Load(Server.mappath("Employee.xml"));
Xmlelement parentelement =
xmldoc.createelement("Details");
271
Xmlelement name = xmldoc.createelement("Name");
Name.innertext = textbox1.Text;
Xmlelement Emp_id =
xmldoc.createelement("Emp_id");
Emp_id.innertext = textbox2.Text;
Xmlelement Qualification =
xmldoc.createelement("Qualification");
Qualification.innertext =
dropdownlist1.selecteditem.Text;
Parentelement.appendchild(name);
Parentelement.appendchild(Emp_id);
Parentelement.appendchild(Qualification);
Xmldoc.documentelement.appendchild(parentelement);
Xmldoc.Save(Server.mappath("Employee.xml"));
Binddatalist();
Save.jpg
272
Step 8 : See your sample.xml file, it will include the data
that I entered at the run time like this:
<?Xmlversion="1.0"encoding="utf-8"?>
<employeeinformation>
<Details>
<Name>Richa</Name>
<Emp_id>1</Emp_id>
<Qualification>MCA</Qualification>
</Details>
</employeeinformation>
273
PROGRAMS/PROJECTS
PROGRAM 1
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Namespace consoleapplication1
Class Program
Int i = 0;
274
Console.writeline("Even Numbers :");
If( i%2 == 0 )
If (i % 2 != 0)
Console.writeline();
275
}
Output
Even Numbers :
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
42 44 46 48 50
Odd Numbers :
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
41 43 45 47 49
276
PROGRAM 2
Using System;
Int n1=0,n2=1,n3,i,number;
Number = int.Parse(Console.readline());
N3=n1+n2;
Console.Write(n3+" ");
N1=n2;
N2=n3;
277
}
Output:
278
PROGRAM 3
Using System;
Int i,fact=1,number;
Number= int.Parse(Console.readline());
For(i=1;i<=number;i++){
Fact=fact*i;
279
Output:
280
PROGRAM 4
Using System;
Char ch='A';
Int i, j, k, m;
Console.Write(" ");
For(k=1;k<=i;k++)
Console.Write(ch++);
Ch--;
For(m=1;m<i;m++)
Console.Write(--ch);
281
Console.Write("\n");
Ch='A';
Output:
ABA
ABCBA
ABCDCBA
ABCDEDCBA
282
PROGRAM 5
283
Program:-
Dim cal, tax, bs, da, hra, ma, pf, pt, it As Integer
Bs = cint(textbox2.Text)
Da = cint(textbox3.Text)
Hra = cint(textbox4.Text)
Ma = cint(textbox5.Text)
Pf = cint(textbox6.Text)
Pt = cint(textbox7.Text)
It = cint(textbox8.Text)
Textbox9.Text = cal
End Class
Output:-
285
PROGRAM 6
Program:-
Combobox1.Items.Add("Question1")
286
Combobox1.Items.Add("Question2")
Combobox1.Items.Add("Question3")
Radiobutton1.Visible = False
Radiobutton2.Visible = False
Radiobutton3.Visible = False
Radiobutton4.Visible = False
End Sub
Else
End If
End If
End If
End If
Else
End If
End If
End Sub
Radiobutton1.Visible = True
Radiobutton2.Visible = True
Radiobutton3.Visible = True
288
Radiobutton4.Visible = True
Textbox2.Text = ""
Radiobutton1.Checked = False
Radiobutton2.Checked = False
Radiobutton3.Checked = False
Radiobutton4.Checked = False
Radiobutton2.Text = "Mumbai"
Radiobutton3.Text = "Pune"
Radiobutton4.Text = "Chennai"
Textbox2.Text = ""
Radiobutton1.Checked = False
Radiobutton2.Checked = False
Radiobutton3.Checked = False
289
Radiobutton4.Checked = False
Radiobutton3.Text = "California"
Radiobutton4.Text = "Georgia"
Textbox2.Text = ""
Radiobutton1.Checked = False
Radiobutton2.Checked = False
Radiobutton3.Checked = False
Radiobutton4.Checked = False
Radiobutton1.Text = "Frankfurt"
Radiobutton3.Text = "Hamburg"
Radiobutton4.Text = "Berlin"
End If
End Sub
290
End Class
Output:-
291
PROGRAM 7
Program:-
Combobox1.Items.Add("BCA")
Combobox1.Items.Add("BSC")
Combobox1.Items.Add("MCA")
Splitcontainer1.Panel2.Hide()
292
End Sub
Splitcontainer1.Panel2.Show()
Label26.Text = textbox1.Text
Label25.Text = textbox2.Text
Label24.Text = textbox3.Text
Label23.Text = combobox1.selecteditem()
Label22.Text = radiobutton1.Text
Label22.Text = radiobutton2.Text
End If
Label21.Text = datetimepicker1.Value
Label20.Text = textbox4.Text
Label19.Text = textbox5.Text
End Sub
End Class
293
Output:-
294
PROGRAM 8
Program:-
Dim a, b As String
A = checkbox1.Text
A = checkbox2.Text
295
Elseif checkbox3.Checked = True Then
A = checkbox3.Text
End If
B = radiobutton1.Text
B = radiobutton2.Text
B = radiobutton3.Text
End If
End Sub
End Class
296
Output:-
297
PROGRAM 9
FYBCA.VB
Inherits student
Dim i As Integer = 0
Submark(i) = value
I += 1
End Set
298
Get
Return submark.Sum
End Get
End Property
End Class
SYBCA.VB
Inherits student
Dim i As Integer = 0
Submark(i) = value
I += 1
End Set
Get
Return submark.Sum
End Get
299
End Property
End Class
TYBCA.VB
Inherits student
Dim i As Integer = 0
Submark(i) = value
I += 1
End Set
Get
Return submark.Sum
End Get
End Property
End Class
Student.vb
300
Public Class student
Rollno = value
End Set
Get
Return rollno
End Get
End Property
Totalmarks = value
End Set
Get
Return totalmarks
End Get
301
End Property
Studentname = value
End Set
Get
Return studentname
End Get
End Property
Totalmarks = i
Return totalmarks / 4
End Function
End Class
Form1.vb
Private i As Short
302
Private Sub Form1_Load(sender As Object, e As
eventargs) Handles mybase.Load
Sub1.Visible = False
Sub2.Visible = False
Sub3.Visible = False
Sub4.Visible = False
End Sub
Changeyear()
Fybca.forecolor = Color.Black
Sub2name.Text = "HTML"
Sub4name.Text = "DBMS-1"
I=1
End Sub
303
Changeyear()
Sybca.forecolor = Color.Black
Sub2name.Text = "VB.NET"
Sub3name.Text = "DBMS-2"
I=2
End Sub
Changeyear()
Tybca.forecolor = Color.Black
Sub1name.Text = "JAVA"
Sub2name.Text = "ASP.NET"
I=3
End Sub
Sub changeyear()
304
Sub1.Clear()
Sub2.Clear()
Sub3.Clear()
Sub4.Clear()
Sub1.Visible = True
Sub2.Visible = True
Sub3.Visible = True
Sub4.Visible = True
Totaldisplay.Text = ""
Persdisplay.Text = ""
Fybca.forecolor = Color.White
Sybca.forecolor = Color.White
Tybca.forecolor = Color.White
End Sub
Dispresult.Click
If i = 1 Then
Fystudent.calculatemark = Val(sub2.Text)
Fystudent.calculatemark = Val(sub3.Text)
Fystudent.calculatemark = Val(sub4.Text)
Elseif i = 2 Then
Systudent.calculatemark = Val(sub1.Text)
Systudent.calculatemark = Val(sub2.Text)
Systudent.calculatemark = Val(sub3.Text)
Systudent.calculatemark = Val(sub4.Text)
Elseif i = 3 Then
Tystudent.calculatemark = Val(sub2.Text)
Tystudent.calculatemark = Val(sub3.Text)
Tystudent.calculatemark = Val(sub4.Text)
Else
End If
End Sub
End Class
307
308
PROGRAM 10
// htmlcontrolsExample:.aspx
Inherits="asp.netExample:.htmlcontrolsExample:" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>
309
</div>
</form>
</body>
</html>
// htmlcontrolsExample:.aspx.cs
Using System;
Namespace asp.netExample:
String a = Request.Form["Text1"];
Response.Write(a);
310
}
Output:
311
PROGRAM 11
Try
Con.Open();
Da.selectcommand.executenonquery();
Messagebox.Show("Account created
successfully..");
Cleardata();
Catch
313
{
Messagebox.Show("Error occured...");
Finally
Con.Close();
Txtname.Text = "";
Txtemailid.Text = "";
Txtloginid.Text = "";
Txtpassword.Text = "";
Txtconpassword.Text = "";
314
Here is above code I have saved the data into the
database. After saving the record a message will show
and later all the records have been cleared. Now let’s run
the application and check the output. For this I have
created a table named as userlogin.
315
316
PROGRAM 12
317
318
1. Adding Controls to the form
// webcontrols.aspx
319
14. .auto-style3 {
15. Width: 278px;
16. Height: 23px;
17. }
18. .auto-style4 {
19. Height: 23px;
20. }
21. </style>
22. </head>
23. <body>
24. <form id="form1" runat="server">
25. <div>
26. <table class="auto-style1">
27. <tr>
28. <td>
29. <asp:Label ID="Label1" runat="server" Text="User
Name"></asp:Label>
30. </td>
31. <td>
32. <asp:textbox ID="username" runat="server"
required="true"></asp:textbox></td>
33. </tr>
34. <tr>
35. <td>
36. <asp:Label ID="Label6" runat="server"
Text="Email ID"></asp:Label>
37. </td>
38. <td>
39. <asp:textbox ID="emailid" runat="server"
textmode="Email"></asp:textbox></td>
320
40. </tr>
41. <tr>
42. <td>
43. <asp:Label ID="Label2" runat="server"
Text="Password"></asp:Label></td>
44. <td>
45. <asp:textbox ID="textbox2" runat="server"
textmode="Password"></asp:textbox></td>
46. </tr>
47. <tr>
48. <td>
49. <asp:Label ID="Label3" runat="server"
Text="Confirm Password"></asp:Label></td>
50. <td>
51. <asp:textbox ID="textbox3" runat="server"
textmode="Password"></asp:textbox></td>
52. </tr>
53. <tr>
54. <td>
55. <asp:Label ID="Label4" runat="server"
Text="Gender"></asp:Label></td>
56. <td>
57. <asp:radiobutton ID="radiobutton1"
runat="server" groupname="gender" Text="Male"
/>
58. <asp:radiobutton ID="radiobutton2"
runat="server" groupname="gender"
Text="Female" /></td>
59. </tr>
60. <tr>
321
61. <td>
62. <asp:Label ID="Label5" runat="server"
Text="Select Course"></asp:Label>s</td>
63. <td>
64. <asp:checkbox ID="checkbox1" runat="server"
Text="J2SEE" />
65. <asp:checkbox ID="checkbox2" runat="server"
Text="J2EE" />
66. <asp:checkbox ID="checkbox3" runat="server"
Text="Spring Framework" />
67. </td>
68. </tr>
69. <tr>
70. <td>
71. </td>
72. <td>
73. <br />
74. <asp:Button ID="Button1" runat="server"
Text="Register" cssclass="btn btn-primary"
onclick="Button1_Click"/>
75. </td>
76. </tr>
77. </table>
78. <asp:Label ID="message" runat="server" Font-
Size="Medium" forecolor="Red"></asp:Label>
79. </div>
80. </form>
81. <table class="auto-style1">
82. <tr>
322
83. <td class="auto-style2"><asp:Label
ID="showusernamelabel" runat="server"
></asp:Label></td>
84. <td>
85. <asp:Label ID="showusername" runat="server"
></asp:Label></td>
86. </tr>
87. <tr>
88. <td class="auto-style2"><asp:Label
ID="showemailidlabel" runat="server"
></asp:Label></td>
89. <td>
90. <asp:Label ID="showemail" runat="server"
></asp:Label></td>
91. </tr>
92. <tr>
93. <td class="auto-style3"><asp:Label
ID="showgenderlabel" runat="server"
></asp:Label></td>
94. <td class="auto-style4">
95. <asp:Label ID="showgender" runat="server"
></asp:Label></td>
96. </tr>
97. <tr>
98. <td class="auto-style2"><asp:Label
ID="showcourselabel" runat="server"
></asp:Label></td>
99. <td>
100. <asp:Label ID="showcourses" runat="server"
></asp:Label></td>
323
101. </tr>
102. </table>
103. </body>
104. </html>
// webcontrols.aspx.cs
1. Using System;
2. Using System.Collections.Generic;
3. Using System.Linq;
4. Using System.Web;
5. Using System.Web.UI;
6. Using System.Web.UI.webcontrols;
7. Namespace webformscontrolls
8. {
9. Public partial class webcontrols :
System.Web.UI.Page
10. {
11. Protected
System.Web.UI.htmlcontrols.htmlinputfile File1;
12. Protected
System.Web.UI.htmlcontrols.htmlinputbutton
Submit1;
13. Protected void Page_Load(object sender, eventargs
e)
324
14. {
15. }
16. Protected void Button1_Click(object sender,
eventargs e)
17. {
1. 18. Message.Text = "Hello " +
username.Text + " ! ";
2. 19. Message.Text = message.Text + "
<br/> You have successfuly Registered with the
following details.";
3. 20. Showusername.Text =
username.Text;
4. 21. Showemail.Text = emailid.Text;
22. If (radiobutton1.Checked)
23. {
24. Showgender.Text = radiobutton1.Text;
25. }
26. Else showgender.Text = radiobutton2.Text;
27. Var courses = "";
28. If (checkbox1.Checked)
29. {
30. Courses = checkbox1.Text + " ";
31. }
32. If (checkbox2.Checked)
33. {
34. Courses += checkbox2.Text + " ";
35. }
36. If (checkbox3.Checked)
37. {
38. Courses += checkbox3.Text;
325
39. }
40. Showcourses.Text = courses;
41. Showusernamelabel.Text = "User Name";
42. Showemailidlabel.Text = "Email ID";
43. Showgenderlabel.Text = "Gender";
44. Showcourselabel.Text = "Courses";
45. Username.Text = "";
46. Emailid.Text = "";
47. Radiobutton1.Checked = false;
48. Radiobutton2.Checked = false;
49. Checkbox1.Checked = false;
50. Checkbox2.Checked = false;
51. Checkbox3.Checked = false;
52. }
53. }
54. }
326
Output:
327
After filling the form and registration, it shows a greeting
message to the user.
328
329
PROGRAM 13
Studentregistratation.aspx
<!DOCTYPE html>
<script runat="server">
End Sub
</script>
<head>
<title>Registration Page</title>
</head>
<body>
330
<fieldset style="width:280px">
<legend>Registration Form</legend>
<table>
<tr>
<td> <asp:requiredfieldvalidator
ID="validfname" runat="server" controltovalidate="txt1"
errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td><asp:requiredfieldvalidator
ID="validlname" runat="server"
Controltovalidate="txt2" errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>
</tr>
<tr>
331
<td>User Name:</td><td> <asp:textbox
id="user" runat="server"></asp:textbox></td>
<td><asp:requiredfieldvalidator
ID="validuser" runat="server" controltovalidate="user"
errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>Password:</td><td><asp:textbox
ID="pwd" runat="server"
textmode="Password"></asp:textbox></td>
<td><asp:requiredfieldvalidator
ID="validpwd" runat="server" controltovalidate="pwd"
errormessage="Required!" forecolor="Red">
</asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>Confirm
Password:</td><td><asp:textbox ID="Textbox1"
runat="server"
textmode="Password"></asp:textbox></td>
</tr>
<tr>
332
<td>Email:</td><td><asp:textbox ID="email"
runat="server" textmode="Email" ></asp:textbox></td>
<td><asp:requiredfieldvalidator
ID="validemail" runat="server"
controltovalidate="email" errormessage="required!"
forecolor="Red"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>Mobile:</td><td><asp:textbox
ID="mobile" runat="server" textmode
="Phone"></asp:textbox></td>
</tr>
<tr>
<td>Gender:</td><td><asp:radiobuttonlist
ID="radiobuttonlist1" runat="server">
<asp:listitem Text="Male"
Value="0"></asp:listitem>
<asp:listitem Text="Female"
Value="1"></asp:listitem>
</asp:radiobuttonlist></td>
</tr>
<tr>
333
<td>DOB: </td><td><asp:textbox ID="dob"
runat="server" textmode="Date"
Width="168px"></asp:textbox> </td>
<td><asp:requiredfieldvalidator ID="validdob"
runat="server" controltovalidate="dob"
errormessage="Required"
forecolor="Red"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>Course: </td><td><asp:dropdownlist
ID="ddlcourse" runat="server" datavaluefield="Course"
Width="173px">
</asp:dropdownlist></td>
<td><asp:requiredfieldvalidator initialvalue="-
1" ID="validcourse" runat="server"
334
controltovalidate="ddlcourse"
errormessage="Required!"
forecolor="Red"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>Nationality:</td><td><asp:checkbox
ID="check" Text="Indian"
runat="server"/><asp:checkbox id="checknat"
Text="Others" runat="server" /></td>
</tr>
<tr>
</tr>
<tr>
<td></td><td><asp:fileupload
ID="imgupload" runat="server" Enabled="true" /></td>
</tr>
<tr>
</tr>
</table>
</fieldset>
</form>
</body>
336
Output:
337
3. Filling the record
338
Implementation of Web Services in asp.Net Applications.
339
creating the Web Service, we will follow the following
steps:
340
After this a new window will be shown us like as shown
below:
341
After this, a new window will appear. From where we
have to click on the Web-> Select Web Service(.asmx
page)-> Give a name to the Web Service as shown in
the below screenshot:
342
After adding the Web Service to the application, a new
window will appear which is shown as below:
343
[webservicebinding(conformsto=
wsiprofiles.basicprofile1_1)] to [webservicebinding
(conformsto = wsiprofiles.None)].
1. [webmethod]
2. Public int sumofnums(int firstnumber, int
secondnumber)
3. {
4. Return firstnumber + secondnumber;
5. }
6.
7. //here we will use messagename property to do
the differentiation between both of the methods.
8. [webmethod(messagename = "sumoffloats")]
9. 9.
10. Public float sumofnums(float firstnumber, float
secondnumber)
11. {
12. Return firstnumber + secondnumber;
13. }
[System.Web.Script.Services.scriptservice]
[webmethod]
Mark-up
345
In the Service1.asmx, we will see that the Service uses
the webservice directive with the attribute. From here,
this will show us that the application invokes the Service,
not by the end-user. Hence the asmx page has no mark-
up.
Service1.asmx
346
<%@ webservice Language="C#"
codebehind="Service1.asmx.cs"
Class="webapplication7.Service1" %
347
There is also another link to the helloworld. After
clicking on this link, this will redirect us to the testing
page.
348
Implementation of web Service
Myservice.asmx
349
Myservice.asmx.cs
1. Using System;
2. Using System.Collections.Generic;
3. Using System.Linq;
4. Using System.Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. [webservicebinding(conformsto =
wsiprofiles.basicprofile1_1)]
16. [System.componentmodel.toolboxitem(false)
]
17. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
18. [System.Web.Script.Services.scriptservice]
19. Public class myservice :
System.Web.Services.webservice
20. {
21.
22. [webmethod]
350
23. Public int sumofnums(int First, int Second)
24. {
25. Return First + Second;
26. }
27. }
28. }
351
Now we will use the OOP (Object Oriented Programming
Concept) concept method overloading. Now we add the
webmethod in the myservice class.
Myservice.asmx.cs
1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. [webservicebinding(conformsto =
wsiprofiles.basicprofile1_1)]
352
16. [System.componentmodel.toolboxitem(false)
]
17. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
18. [System.Web.Script.Services.scriptservice]
19. Public class myservice :
System.Web.Services.webservice
20. {
21.
22. [webmethod(messagename = "sumoffloats")]
23.
24. Public float sumofnums(float First, float
Second)
25. {
26. Return First + Second;
27. }
28.
29. }
30. }
353
After entering the values in the first text box and second
text box, this will invoke the method as shown in the
below screenshot:
Method Overloading
354
overloading. Here we are taking an Example: to show the
method overloading done in the Web Service and throw
an error because it does not support the overloading.
Myservice.asmx.cs
1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. [webservicebinding(conformsto =
wsiprofiles.basicprofile1_1)]
16. [System.componentmodel.toolboxitem(false)
]
17. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
18. [System.Web.Script.Services.scriptservice]
19. Public class myservice :
System.Web.Services.webservice
355
20. {
21.
22. [webmethod]
23. Public int sumofnums(int First, int Second)
24. {
25. Return First + Second;
26. }
27. [webmethod(messagename = "sumoffloats")]
28.
29. Public float sumofnums(float First, float
Second)
30. {
31. Return First + Second;
32. }
33.
34. }
35. }
1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.Services;
6. Using System.Web.Script.Serialization;
7.
8.
9. Namespace webapplication7
10. {
11. /// <summary>
12. /// Summary description for Service1
13. /// </summary>
14. [webservice(Namespace =
"http://tempuri.org/")]
15. //make the wsiprofiles to None
16. [webservicebinding(conformsto =
wsiprofiles.None)]
17. [System.componentmodel.toolboxitem(false)
]
357
18. // To allow this Web Service to be called
from script, using ASP.NET AJAX, uncomment
the following line.
19. [System.Web.Script.Services.scriptservice]
20. Public class myservice :
System.Web.Services.webservice
21. {
22.
23. [webmethod]
24. Public int sumofnums(int First, int Second)
25. {
26. Return First + Second;
27. }
28.
29. //here we have to add the messagename
property to make the difference between
both of the methods.
30. [webmethod(messagename = "sumoffloats")]
31. 31.
32. Public float sumofnums(float First, float
Second)
33. {
34. Return First + Second;
35. }
36.
37. }
38. }
After all these changes the Web Service will looks like as
shown in the below screenshot:
358
Here web service supports the method with the same
name. By adding the message name property, we can
create the differences between both of the methods.
359
http://localhost:62639/myservice.asmx/sumoffloats,
which is having the value where the sumofnums method
returns the XML format.
Test Pages are not part of the Web Service. Test Page is
rendered by the ASP.NET by using the Web Page
c:\[windir]\Microsoft. NET\Framework\ [Version]
\Config\defaultwsdlhelpgenerator.aspx. "Reflection"
concept renders to the test page.
WSDL Document
362
Step2: After clicking on the New Project a new window
will open as shown in the below screenshot:
Proxy Class
363
After clicking on the Add Service Reference, a new
window will appear as shown in the below screenshot:
364
Right-click on the project in the solution explorer->
select add->choose web form as shown in the below
screenshot:
365
Here in the above screenshot, we gave the name of the
web form and then click on OK.
366
17. <asp:textbox ID="txtfirstnumber"
runat="server"></asp:textbox>
18. </td>
19. </tr>
20. <tr>
21. <td>
22. <b>Second Number</b>
23. </td>
24. <td>
25. <asp:textbox ID="txtsecondnumber"
runat="server"></asp:textbox>
26. </td>
27. </tr>
28. <tr>
29. <td>
30. <b>Result</b>
31. </td>
32. <td>
33. <asp:Label ID="lblresult" runat="server"
Text="Label"></asp:Label>
34. </td>
35. </tr>
36. <tr>
37. <td>
38. <asp:Button ID="btnadd" runat="server"
Text="Add" onclick="btnadd_Click" />
39. </td>
40.
41.
42. </tr>
367
43. </table>
44. </form>
45. </body>
46. </html>
368
Webform.aspx.cs
1. Using System;
2. Using System.Collections.Generic;
3. Using System. Linq;
4. Using System. Web;
5. Using System.Web.UI;
6. Using System.Web.UI.webcontrols;
7. 7.
8. Namespace calculatorwebapplication
9. {
10. Public partial class webform1 :
System.Web.UI.Page
11. {
12. Protected void Page_Load(object sender, eventargs
e)
13. {
14. 14.
15. }
16. 16.
17. Protected void btnadd_Click(object sender,
eventargs e)
18. {
19. Calculatorservice.calculatorwebservicesoapclient
client = new
calculatorservice.calculatorwebservicesoapclient()
;
20. Int result=
client.Add(Convert.toint32(txtfirstnumber.Text),
21. Convert.toint32(txtsecondnumber.Text));
369
22. Lblresult.Text = result.tostring();
23. }
24. }
25. }
370
371