ASP.NET

You might also like

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

ASP.

NET WITH C#

ASP.NET framework:
 .NET is a framework to develop software applications.
 It is designed and developed by Microsoft and the first beta version released in 2000.
 It is used to develop applications for web, Windows, phone. Moreover, it provides a broad
range of functionalities and support.
 The .Net Framework supports more than 60 programming languages such as C#, F#,
VB.NET, J#, VC++, JScript.NET, APL, COBOL, Perl, Oberon, ML, Pascal, Eiffel, Smalltalk,
Python, Cobra, ADA, etc.

The .NET Framework is composed of four main components:


 Common Language Runtime (CLR)
 Framework Class Library (FCL),
 Core Languages (WinForms, ASP.NET, and ADO.NET), and
 Other Modules (WCF, WPF, WF, Card Space, LINQ, Entity Framework, Parallel LINQ,
Task Parallel Library, etc.)

CLR (Common Language Runtime):


 It is a program execution engine that loads and executes the program.
 It converts the program into native code. It acts as an interface between the framework
and operating system.
 It does exception handling, memory management, and garbage collection.
 Moreover, it provides security, type-safety, interoperability, and portability.
 .Net applications are written in C #, F #, or Visual Basic programming languages. The
code is compiled into the Microsoft Intermediate Language (MSIL). The compiled code
is stored in the assembly – files with .dll file extension. Or exe.
 CLR converts MSIL into machine code using a compiler in time (JIT) that can be executed
on the specific architecture of the computer on which it is running.
Working of CLR

CLS (Common Language Specification):


 CLS stands for Common Language Specification and it is part of CLR.
 It defines a set of rules and restrictions that every language must follow which runs
under the .NET framework.
 The languages which follow these set of rules are said to be CLS Compliant. In simple
words, CLS enables cross-language integration or Interoperability.

For Example:
 if we talk about C# and VB.NET then, in C# every statement must have to end with a
semicolon. it is also called a statement Terminator, but in VB.NET each statement
should not end with a semicolon(;).

Explanation of the above Example


 So these syntax rules which you have to follow from language to language differ but CLR
can understand all the language Syntax because in .NET each language is converted into
MSIL code after compilation and the MSIL code is language specification of CLR.
CTS(Common Type System):
 Common Type System (CTS) describes the datatypes that can be used by managed
code.
 CTS deals with the data type. So here we have several languages and each and every
language has its own data type and one language data type cannot be understandable
by other languages but .NET Framework language can understand all the data types.
 CTS is converting the data type to a common data type, for example, when we declare
an int type data type in C# and VB.Net then they are converted to int32. In other words,
now both will have a common data type that provides flexible communication between
these two languages.

FCL (Framework Class Library):


 It is a standard library that is a collection of thousands of classes and used to build an
application.
 The BCL (Base Class Library) is the core of the FCL and provides basic functionalities.

WinForms:
Windows Forms is a smart client technology for the .NET Framework, a set of managed libraries
that simplify common application tasks such as reading and writing to the file system.
ASP.NET:
ASP.NET is a web framework designed and developed by Microsoft. It is used to develop
websites, web applications, and web services. It provides a fantastic integration of HTML, CSS,
and JavaScript. It was first released in January 2002.
ADO.NET:
ADO.NET is a module of .Net Framework, which is used to establish a connection between
application and data sources. Data sources can be such as SQL Server and XML. ADO .NET
consists of classes that can be used to connect, retrieve, insert, and delete data.

LINQ (Language Integrated Query):


It is a query language, introduced in .NET 3.5 framework. It is used to make the query for data
sources with C# or Visual Basics programming languages.

 ASP.NET Controls:
 Controls are small building blocks of the graphical user interface, which include
text boxes, buttons, check boxes, list boxes, labels, and numerous other tools.
 Using these tools, the users can enter data, make selections and indicate their
preferences.
 Controls are also used for structural jobs, like validation, data access,
security, creating master pages, and data manipulation.

ASP.NET uses 2 main types of web controls, which are:


 HTML controls
 Server controls

HTML CONTROLS:
 HTML server controls are HTML elements that contain attributes to accessible
at server side.
 By default, HTML elements on an ASP.NET Web page are not available to the
server.
 These components are treated as simple text and pass through to the browser.
 We can convert an HTML element to server control by adding
a runat="server" and an id attribute to the component.
 All the HTML Server controls can be accessed through the Request object.

Now, we can easily access it at code behind.

Example:
<input id="UserName" type="text" size="50"runat="server" />

The following table contains commonly used HTML components.


Controls Name Description

Button It is used to create HTML button.

Reset Button It is used to reset all HTML form elements.

Submit Button It is used to submit form data to the server.

Text Field It is used to create text input.

Text Area It is used to create a text area in the html form.

File It is used to create a input type = "file" component which is used to


upload file to the server.

Password It is a password field which is used to get password from the user.

CheckBox It creates a check box that user can select or clear.

Radio Button A radio field which is used to get user choice.

Table It allows us to present information in a tabular format.

Image It displays an image on an HTML form

ListBox It displays a list of items to the user. You can set the size from two
or more to specify how many items you wish to show.

Dropdown It displays a list of items to the user in a dropdown list.

Horizontal Rule It displays a horizontal line across the HTML page.

Example
Here, we are implementing an HTML server control in the form.

// htmlcontrolsexample.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="htmlcontrolsex
ample.aspx.cs"
Inherits="asp.netexample.htmlcontrolsexample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"
/>
</div>
</form>
</body>
</html>

This application contains a code behind file.

// htmlcontrolsexample.aspx.cs

using System;
namespace asp.netexample
{
public partial class htmlcontrolsexample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string a = Request.Form["Text1"];
Response.Write(a);
}
}
}
Output:

When we click the button after entering text, it responses back to client.

ASP.NET Server Controls


 Runs on the web server.
 All ASP.NET server control have runat="server" attribute, by default.
 Server controls provide state management.
 Its execution is slow compare to HTML control.
 You can access these controls from code-behind.
 Server controls have predefined classes.
 Controls are inherited from System.Web.UI.WebControls name space.

The syntax for using server controls is:


<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] />

 The following table contains the server controls for the web forms.
Control Name Applicable Events Description

Label None It is used to display text on the HTML


page.

TextBox TextChanged It is used to create a text input in the


form.

Button Click, Command It is used to create a button.

LinkButton Click, Command It is used to create a button that looks


similar to the hyperlink.

ImageButton Click It is used to create an imagesButton.


Here, an image works as a Button.

Hyperlink None It is used to create a hyperlink control


that responds to a click event.

DropDownList SelectedIndexChanged It is used to create a dropdown list


control.

ListBox SelectedIndexCnhaged It is used to create a ListBox control like


the HTML control.

CheckBox CheckChanged It is used to create checkbox.

CheckBoxList SelectedIndexChanged It is used to create a group of check boxes


that all work together.

RadioButton CheckChanged It is used to create radio button.

RadioButtonList SelectedIndexChanged It is used to create a group of radio


button controls that all work together.
Image None It is used to show image within the page.

Panel None It is used to create a panel that works as a


container.

PlaceHolder None It is used to set placeholder for the


control.

Calendar SelectionChanged, It is used to create a calendar. We can set


VisibleMonthChanged, the default date, move forward and
DayRender backward etc.

AdRotator AdCreated It allows us to specify a list of ads to


display. Each time the user re-displays the
page.

Table None It is used to create table.

XML None It is used to display XML documents


within the HTML.

Difference between HTML control and Web Server control.

HTML control Web Server control


HTML control runs at client side. ASP.Net controls run at server side.
We can run HTML controls at server side We cannot run ASP.Net Controls on client
by adding attribute runat=”server”. side as these controls have this
attribute runat=”server” by default.
HTML controls are client sidecontrols , ASP.Net Controls are Server side controls,
so it does not provide STATE provides STATE management.
management.
HTML control does not require HTML control does not require rendering.
rendering.
As HTML controls runs on client As ASP.Net controls run on server side,
side,execution is fast. execution is slow.

HTML controls does not With ASP.Net controls, you have full support
support Object Oriented paradigm. of Object oriented paradigm.
HTML control have limited set of ASP.Net controls have rich set of properties
properties and/or methods. and/or methods.
<input type="text" ID="txtName"> <asp:TextBoxId="txtName"runat="server">
</asp:TextBox>

1. Textbox control
This is an input control which is used to take user input. To create TextBox either we can
write code or use the drag and drop facility of visual studio IDE.

This is server side control, asp provides own tag to create it. The example is given below.
< asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox>

Server renders it as the HTML control and produces the following code to the browser.
<input name="TextBox1" id="TextBox1" type="text">

This control has its own properties that are tabled below.
Property Description

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.


Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

MaxLength It is used to set maximum number of characters that can be entered.

Readonly It is used to make control readonly.

Example
// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="labelId" runat="server">User Name</asp:Label>
<asp:TextBox ID="UserName" runat="server" ToolTip="Enter User Name"></asp:TextBox>
</div>
<p>
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Cli
ck" />
</p>
<br />
</form>
<asp:Label ID="userInput" runat="server"></asp:Label>
</body>
</html>

Code Behind
// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void SubmitButton_Click(object sender, EventArgs e)
{
userInput.Text = UserName.Text;
}
}
}

This is a property window of the TextBox control.

Output:
It produces the following output.
It displays user input, when user submits the input to the server. The following screen shot
taking and showing user input.

2. Label:
This control is used to display textual information on the web forms. It is mainly used to
create caption for the other controls like: textbox.

To create label either we can write code or use the drag and drop facility of visual studio.

This is server side control, asp provides own tag to create label. The example is given
below.

1. < asp:LabelID="Label1" runat="server" Text="Label" ></asp:Label>


This control has its own properties that are tabled below.

Property Description

BackColor It is used to set background color of the label.

BorderColor It is used to set border color of the label.

BorderWidth It is used to set width of border of the label.

Font It is used to set font for the label text.

ForeColor It is used to set color of the label text.

Text It is used to set text to be shown for the label.

ToolTip It displays the text when mouse is over the label.


Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

3. button
This control is used to perform events. It is also used to submit client request to the server.
To create Button either we can write code or use the drag and drop facility of visual studio
IDE.

This is a server side control and asp provides own tag to create it. The example is given
below.

1. < asp:ButtonID="Button1" runat="server" Text="Submit" BorderStyle="Solid" ToolTip="


Submit"/>

Server renders it as the HTML control and produces the following code to the browser.

1. <input name="Button1" value="Submit" id="Button1" title="Submit" style="border-


style:Solid;" type="submit">

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.


Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

Example
// WebControls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Click here" OnClick="Button1_Click" />
</div>
</form>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</body>
</html>

Code Behind
// WebControls.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "You Clicked the Button.";
}
}
}

Output:
It produces the following output.

This button displays a message when clicked, as shown below.


4. Radiobutton
It is an input control which is used to takes input from the user. It allows user to select a
choice from the group of choices.

To create RadioButton we can drag it from the toolbox of visual studio.

This is a server side control and ASP.NET provides own tag to create it. The example is
given below.

1. < asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupName="gender"/>

Server renders it as the HTML control and produces the following code to the browser.

1. <input id="RadioButton1" type="radio" name="gender" value="RadioButton1" /><labelforlab


elfor="RadioButton1">Male</label>

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.


ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

GroupName It is used to set name of the radio button group.

Example
In this example, we are creating two radio buttons and putting in a group named
gender.
// WebControls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="gender" />

<asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="gender" />

</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" style="w
idth: 61px" />
</p>
</form>
<asp:Label runat="server" id="genderId"></asp:Label>
</body>
</html>

Code Behind
// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
genderId.Text = "";
if (RadioButton1.Checked)
{
genderId.Text = "Your gender is "+RadioButton1.Text;
}
else genderId.Text = "Your gender is "+RadioButton2.Text;
}
}
}

For this control we have set some properties like this:


Output:
It produces the following output to the browser.

It responses back to the client when user select the gender.


5. Checkbox:
It is used to get multiple inputs from the user. It allows user to select choices from the set
of choices.
It takes user input in yes or no format. It is useful when we want multiple choices from the
user.
To create CheckBox we can drag it from the toolbox in visual studio.

This is a server side control and ASP.NET provides own tag to create it. The example is
given below.
1. < asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>

Server renders it as the HTML control and produces the following code to the browser.

1. < input id="CheckBox2" type="checkbox" name="CheckBox2" /><label for="CheckBox2">J2E


E</label>

This control has its own properties that are tabled below.

Property Description

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.


Height It is used to set height of the control.

Width It is used to set width of the control.

Checked It is used to set check state of the control either true or false.

Example
// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Select Courses</h2>
<asp:CheckBox ID="CheckBox1" runat="server" Text="J2SE" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE" />
<asp:CheckBox ID="CheckBox3" runat="server" Text="Spring" />
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</p>
</form>
<p>
Courses Selected: <asp:Label runat="server" ID="ShowCourses"></asp:Label>
</p>
</body>
</html>
Code Behind
// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShowCourses.Text = "None";
}
protected void Button1_Click(object sender, EventArgs e)
{
var message = "" ;
if (CheckBox1.Checked)
{
message = CheckBox1.Text+" ";
}
if (CheckBox2.Checked)
{
message += CheckBox2.Text + " ";
}
if (CheckBox3.Checked)
{
message += CheckBox3.Text;
}
ShowCourses.Text = message;
}
}
}
Initially, there is no course selected then it shows none. It displays user selection as shown
in the following screenshot.

6. Dropdown list:
The DropDownList is a web server control which is used to create an HTML Select
component. It allows us to select an option from the dropdown list. It can contain any
number of items

ASP.NET provides a tag to create DropDownList for web application. The following is the
Syntax of DropDownList tag.

<asp:DropDownList id="DropDownList1" runat="server"


DataSource="<% databindingexpression %>"
DataTextField="DataSourceField"
DataValueField="DataSourceField"
AutoPostBack="True|False"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod">
<asp:ListItem value="value" selected="True|False">
Text
</asp:ListItem>
</asp:DropDownList>

ASP.NET DropDownList Example

We are creating DropDownList by using Visual Studio 2017. This example includes the
following steps.

Create a Web Form


Add a new form by specifying its name.

Initially, it is an empty form. Now, we will add a new DropDownList by dragging it from the
toolbox.

After dragging, our web form looks like the below.


Now, to add items to the list, visual studio provides Items property where we can add
items. The property window looks like this.

Click on the items (collection) and it will pop up a new window as given below. Initially, it
does not have any item. It provides add button to add new items to the list.
Adding item to the DropDownList, by providing values to the Text and Value properties.

We have added more items to it and now, it looks like the following.

After clicking OK,

DropDownListExample.aspx

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"


CodeBehind="Default.aspx.cs" Inherits="DropDownListExample._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>Select a City of Your Choice</p>
<div>
<asp:DropDownList ID="DropDownList1" runat="server" >
<asp:ListItem Value="">Please Select</asp:ListItem>
<asp:ListItem>New Delhi </asp:ListItem>
<asp:ListItem>Greater Noida</asp:ListItem>
<asp:ListItem>NewYork</asp:ListItem>
<asp:ListItem>Paris</asp:ListItem>
<asp:ListItem>London</asp:ListItem>
</asp:DropDownList>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<br />
<asp:Label ID="Label1" runat="server" EnableViewState="False"></asp:Label>
</form>
</body>
</html>

// DropDownListExample.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DropDownListExample
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "")
{
Label1.Text = "Please Select a City";
}
else
Label1.Text = "Your Choice is: " + DropDownList1.SelectedValue;
}
}
}
Output:

At server side, selected city is fetched and display to the user.

7. List-Box:
 List box control in ASP.Net is a web control derived from the List Control Class, which
in turn is derived from System.Web.UI.WebControls class.
 It allows the selection of single and multiple items in the list, unlike the dropdown list
control, which enables the selection of a single item at a time; this list can also be
bound to the data source.

Syntax:
The list box control can be dragged and dropped from the ASP.Net toolbox on the web
form created, following the code in the .cs file.
<asp: ListBox id="ListBox1" Rows="6" Width="100px" SelectionMode="Single"
runat="server"> </asp: ListBox>
Vice versa, writing the above code in a .cs file creates a list box control on the web form.
The following code can be used to add the elements to the list.
<asp: ListItem>Item 1</asp: ListItem>
Properties of ASP.NET ListBox
1. Items.Count: Returns the total number of items in the list box.
2. Items.Clear: Clears all the items from the list box.
3. SelectedItem.Text: Returns the text of the selected item.
4. Items.Remove(“name”): Removes the item with the text “name.”
5. Items.RemoveAt(int index): Removes the item present at the given index.
6. Items.Insert(int index, “text”): Inserts the “text” at the given index.
7. SelectedItem: Returns the index of the selected item.
8. SelectionMode: Specifies the selection mode as “single or multiple.”

Example #1
Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"


Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> An example of ASP.Net ListBox</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Choose a color:</h2>
<asp: ListBox ID ='ListBox1’ runat = 'server' AutoPostBack = 'true' Font-Size = 'X-Large'
Rows = '5'
ForeColors = 'Tomato' Width = '350' >
<asp: ListItem> Dark Grey </asp: ListItem>
<asp: ListItem> Red </asp: ListItem>
<asp: ListItem> Green </asp: ListItem>
<asp: ListItem> Blue </asp:ListItem>
<asp: ListItem> Yellow </asp: ListItem>
<asp: ListItem> Black </asp: ListItem>
</asp: ListBox>
</div>
</form>
</body>
</html>
You can access the list and make necessary changes using the ID value “ListBox1” in the
code.
Output:

9. Radiobutton list:
RadioButton List class is derived from the Web Control class which
groups the radio button controls. This immensely helps programmers
by providing a single selection radio button group. This group can
also be generated dynamically with the help of data binding.

Syntax
<asp:RadioButtonList AppendDataBoundItems="True|False"
AutoPostBack="True|False" CssClass="string"
DataMember="string" DataSource="string" DataSourceID="string"
DataTextField="string" DataTextFormatString="string"
DataValueField="string" ID="string"
OnDataBinding="Databinding event handler" OnDataBound="Data
Bound event handler"
OnSelectedIndexChanged="SelectedIndexChanged event handler"
OnTextChanged="Text Changed event handler"
RepeatColumns="integer" RepeatDirection="Horizontal|Vertical"
RepeatLayout="Table|Flow|OrderedList|UnorderedList"
runat="server" SelectedIndex="integer"
SelectedValue="string" Visible="True|False" Width="size" >
<asp:ListItem Enabled="True|False" Selected="True|False"
Text="string" Value="string" />
</asp: RadioButtonList>

A typical radio button list would look as below

<asp:RadioButtonList ID="rblRadioButtonListExample"
AppendDataBoundItems="True" AutoPostBack="True"
DataMember="ABC" DataSource="test" DataSourceID="dbTest"
DataTextField="Name" DataTextFormatString="Bold"
DataValueField="txtName" OnDataBinding=" BtnSubmit_Click"
OnDataBound=" BtnSubmit_Click"
OnSelectedIndexChanged="TxtID_LostFocus"
OnTextChanged="txtID_TextChanged" RepeatColumns="1"
RepeatDirection="Horizontal " RepeatLayout="Table "
runat="server" Visible="true" Width="30" >
<asp:ListItem Enabled="True" Selected="True" Text="Name"
Value="CBA" />
</asp:RadioButtonList>

Properties of radiobutton list:


 DataTextField
Text Field property specifies the text of the field that will bound to the RadioButton in
the list.
 DataTextFormatString
Specifies the format of how the data bound to the radio button control will be
displayed.
 DataValueField
Specifies the actual value of the field that is bound using the binding properties.
 OnSelectedIndexChanged
This method is inherited from the List control, it raises the SelectedIndexChanged
event of the radio button control.
 RepeatLayout
The repeat layout helps us to specify how the list will be rendered that is either by
using the <table> element or <ul> element or <span> element.
 Visible
It is the Boolean property, if set to true the radio button list is displayed on the client-
side, if set to false, the control is hidden.
 RepeatColumns
Specifies the number of columns to be displayed in the list when the control is
rendered.
 RepeatDirection
Specifies if the control will be displayed horizontally or vertically.
 Items
Returns the collection of items present in the list.

Form Validation:
Validation controls are an essential part of ASP.NET web development because they help
ensure the integrity of user input. When users enter information into web forms, there is always
the potential for intentional or unintentional errors. Validation controls provide a way to check
the accuracy and validity of user input before the web application processes it.

Client-side validation vs. server-side validation in ASP.NET

ASP.NET supports two types of validation controls:

1. Client-side validation controls


2. Server-side validation controls

Client-side validation is good, but we must depend on browser and scripting language
support. The client-side validation is done in the user's browser using JavaScript and
another scripting. You can use client-side validation libraries such as WebUIValidation.js
in .NET.

Server-side validation in ASP.NET is done in the C# code-behind, where the value of the
user input is read and validated on the server. This process is time-consuming but
provides better security and is easier to implement in ASP.NET. For example, if an app
wants to check the date range, the date value will be read from ASP.NET in C#, and the
C# code behind the validation method will be compared against the rules.

Validation Controls in ASP.NET

ASP.NET provides several types of validation controls that can be used to validate user input in
web forms. Some of the common validation controls are:
The below table describes the controls and their use.

Validation Control Description


This control ensures that a field is not left empty or blank. It can
RequiredFieldValidation be used for textboxes, dropdown lists, checkboxes, and other
input controls.
This control compares the value of one input control to another. It
CompareValidator can validate passwords, confirm email addresses, and other
scenarios where two values must match.
This control checks if a value falls within a specific range. For
RangeValidator example, it can be used to validate a user's age, income, or date
of birth.
This control displays a report of all validation errors that occurred
ValidationSummary
on a Web page.

Important points for validation controls


 ControlToValidate property is mandatory for all validate controls.
 One validation control will validate only one input control, but multiple
validation control can be assigned to the input control.
 To use any validation control following code must be added in web.config
file.
<configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode"
value="None"> </add>
</appSettings>
</ configuration>

1. ASP.NET RequiredFieldValidation Control


 The RequiredFieldValidator control is simple validation control that checks to see
if the data is entered for the input control. You can have a RequiredFieldValidator
control for each form element you wish to enforce the mandatory field rule. It
has foolowing properties
 ControlToValidate
 ErrorMessage
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
Style="top: 98px; left: 367px; position: absolute; height: 26px; width: 162px"
ErrorMessage="password required" ControlToValidate="TextBox2">
</asp:RequiredFieldValidator>

2. ASP.NET CompareValidator Control


 The CompareValidator control allows you to make comparisons to compare data
entered in an input control with a constant value or a value in a different control.
 It can most commonly be used when you need to confirm the password entered
by the user at registration time. The data is always case-sensitive.
 It has foolowing properties
 ControlToValidate
 ControlToCompare
 ErrorMessage

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"


ErrorMessage="password required" ControlToValidate="TextBox3"
ControlToCompare=”Textbox2”>
</asp:RequiredFieldValidator>

3. ASP.NET RangeValidator Control


 The RangeValidator Server Control is another validator control that checks to see
if a control value is within a valid range.
 The attributes necessary for this control are MaximumValue, MinimumValue, and
Type.

<asp:RangeValidator ID="RangeValidator1" runat="server"


ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumValue="100"
MinimumValue="18" Type="Integer">
</asp:RangeValidator>
USER CONTROL
 A User Control is a reusable page or control with an extension of .ascx and
created similar to an .aspx page but the difference is that a User Control does not
render on its own, it requires an .aspx page to be rendered.
 User Controls are very useful to avoid repetition of code for similar requirements.
Suppose I need a calendar control in my application with some custom
requirements in multiple pages, then instead of creating the control repetitively
you can create it once and use it on multiple pages.

Key points
 The User Control page structure is similar to the .aspx page but a User Control does
not need to add an entire HTML structure such as body, head and form.
 A User Control has an .ascx extension.
 A User Control is derived from the UserControl class whereas an .aspx page is
derived from the Page class.
 A User Control does not render on its own, it needs an .aspx page.
 To use a User Control in an .aspx page you need to register the control in the .aspx
page.

How to create a User Control

Step 1: Create Web Application


Open Visual Studio.
1. "File" -> "New" -> "Project..." then select ASP.NET Webform Application.
2. Add a new web form.

Step 2: Create the User Control


1. Then right-click on the project in the Solution Explorer then select "Add New Item"
then select Web User Control template as in the following:
Now click on Add then User Control will be added into the solution of the application.
Now open the design mode and add the two textboxes, one label, one button and after
adding the studentcontrol.ascx the source code will look as follows:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="StudentUserControl.a
scx.cs" Inherits="StudentUserControl" %>

<h3>This is User Contro1 </h3>


Name:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox> <br>

City <asp:TextBox ID="txtcity" runat="server"></asp:TextBox> <br>

<asp:Button ID="txtSave" runat="server" Text="Save" onclick="txtSave_Click" />


<asp:Label ID="Label1" runat="server" ForeColor="White" Text=" ">
</asp:Label>

In the preceding code you have noticed that there is no whole HTML code in User
Control such as head, body and form even then it will create the server control. Now
switch to design mode then the control will look such as follows:

Now double-click on the save button and write the following code in the
studentusercontrol.ascx.cs file as:

protected void txtSave_Click(object sender, EventArgs e)


{
Label1.Text="Your Name is "+txtName.Text+" and you are from "+txtcity.Text;
}

Step 3: Adding User Control into .aspx page


To use a User Control in an .aspx we need to register it using the Register page directive
in .ascp file, the register page directive has the following properties as:

 Src: Used to set the source of User Control.


 TagName: Used to provide the name for the User Control used on a page similar
to a TextBox or label, you can define any name.
 TagPrefix: This is used to specify the prefix name of User Control which is similar
to ASP: You can define any prefix name.

Add a web form names “default.aspx” and add following code to use user control.

<%@ Register Src="~/StudentUserControl.ascx" TagPrefix="uc" TagName="Student"%>


Now the whole code of the default .aspx code will look as in the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits


="_Default" %>

<%@ Register Src="~/StudentUserControl.ascx" TagPrefix="uc" TagName="Student"%>

<html>
<head id="Head1" runat="server">
<title>Article by Vithal Wadje</title>
</head>
<body bgcolor="blue">
<form id="form2" runat="server">
<div style="color: White;">

<uc:Student ID="studentcontrol" runat="server" />

</div>
</form>
</body>
</html>

Adrotator Control
The AdRotator control randomly selects banner graphics from a list, which is specified in
an external XML schedule file. This external XML schedule file is called the advertisement
file.
The AdRotator control allows you to specify the advertisement file and the type of
window that the link should follow in the AdvertisementFile and the Target property
respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />
Before going into the details of the AdRotator control and its properties, let us look into
the construction of the advertisement file.
The Advertisement File
 The advertisement file is an XML file, which contains the information about the
advertisements to be displayed.
 Extensible Markup Language (XML) is a W3C standard for text document markup.
It is a text-based markup language that enables you to store data in a structured
format by using meaningful tags. The term 'extensible' implies that you can extend
your ability to describe a document by defining meaningful tags for the application.
 XML is not a language in itself, like HTML, but a set of rules for creating new markup
languages. It is a meta-markup language. It allows developers to create custom tag
sets for special uses. It structures, stores, and transports the information.
Following is an example of XML file:
<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a structured text file with well-
defined tags delineating the data. There are the following standard XML elements that
are commonly used in the advertisement file:
Element Description

Advertisements Encloses the advertisement file.

Ad Delineates separate ad.

ImageUrl The path of image that will be displayed.

NavigateUrl The link that will be followed when the user clicks the ad.

AlternateText The text that will be displayed instead of the picture if it


cannot be displayed.

Keyword Keyword identifying a group of advertisements. This is used


for filtering.
Impressions The number indicating how often an advertisement will
appear.

Height Height of the image to be displayed.

Width Width of the image to be displayed.


The following code illustrates an advertisement file ads.xml.Add an xml file from solution
explorer and write following code into that.
<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>

<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>

<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>

<Ad>
<ImageUrl>rose4.jpg</ImageUrl>
<NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>

Working with AdRotator Control


Create a new web page and place an AdRotator control on it.

<form id="form1" runat="server">


<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile ="~/ads.xml" />
</div>
</form>

State management:
State Management can be defined as the technique or the way by which we can
maintain / store the state of the page or application until the User's Session ends.

What is the need of State Management?


 Let us assume that someone is trying to access a banking website and he has to fill in
a form.
 So the person fills in the form and submits it. After submission of the form, the
person realizes he has made a mistake. So he goes back to the form page and he sees
that the information he submitted is lost. So he again fills in the entire form and
submits it again. This is quite annoying for any user. So to avoid such problems
"STATE MANAGEMENT" acts as a savior.

ASP.Net State Management Techniques

ASP.NET provides us with 2 ways to manage the state of an application. It is basically


divided into the 2 categories:
1. Client Side State Management.
2. Server Side State Management.

1. Client Side State Management


 It is a way in which the information which is being added by the user or the
information about the interaction happened between the user and the server is
stored on the client's machine or in the page itself.
 The server resources (e.g. server's memory) is not at all utilized during the process.

This management technique basically makes use of the following:


a. View State
b. Cookies
c. Query String

a. View State
 View State can be used to maintain the State at a page level.
 The term "Page Level" means that the information is being stored for a specific
page and until that specific page is active (i.e. the page which is being currently
viewed by the user).
 Once the user is re-directed or goes to some other page, the information stored in
the View State gets lost.
 Using a View State is quite simple. In fact, it is the default way for storing the page
or the control's information.
 Typically the View State is used, when we want a user to be re-directed to the
same page and the information being added by the user remains persistent until
the user is on the same page.

Program:

protected void btn_submit_Click(object sender, EventArgs e)


{
ViewState["a"] = TextBox1.Text;
TextBox1.Text = " ";
}

protected void btn_reset_Click(object sender, EventArgs e)


{
TextBox1.Text = ViewState["a"].ToString();
}
b. COOKIES:
 A cookie is a small text file used to identify users uniquely. It is located on the
client’s computer; it is not stored in the server’s memory.
 You can say a cookie is a small file generated and kept on the client’s machine that
holds information about the user. When a user requests a new page, the server
generates a cookie and delivers it to the client, along with the requested page. The
client then receives and keeps that cookie either permanently, or temporarily, in
the browser.

There are two types of Cookies:


 Persistence Cookies
 Non-Persistence Cookies

 Persistence Cookies
Cookies that have a specific expiry date and time are called Persistence cookies.
They maintain the data on the user’s machine (user’s hard disk folder), such as
sign-on information or settings. They expire based on a date assigned by the
webserver. Typically, these are seen as permanent cookies that do not expire.

 Non-Persistence Cookie
Non-Persistence cookies are not stored permanently on the user’s machine. They
maintain information as long as the user accesses the same browser. Once the
browser is closed, the cookie gets discarded.
To create a non-persistence cookie, simply do not add an expiration date.

Program to create a cookie and access its value in next page.


FIRST.ASPX:

HttpCookie hp = new HttpCookie("Login Details");


hp["username"] = TextBox1.Text;
hp["password"] = TextBox2.Text;

Response.Cookies.Add(hp);
hp.Expires = DateTime.Now.AddSeconds(100);
Response.Write("cookies added");
Response.Redirect("second.aspx");

SECOND.ASPX:

protected void Page_Load(object sender, EventArgs e)


{
HttpCookie c = Request.Cookies["Login Details"];
TextBox1.Text = c["username"].ToString();
}

 Login details is name of cookie.


 Response.Cookies.Add(hp); -> it adds the cookie
 hp.Expires = DateTime.Now.AddSeconds(100); -> its sets expiry time of cookie.
 Request.cookies is used is used the fetch the cookie value from browser.

This is how cookies are stored in browser


Rightclick on browser->inspect->application->cookies->localhost

c. Query String
 In query string data is passed in url in key value pair.
 Query string is mostly used to fetch data from one page to another
 And while redirecting to another page we pass values.
 You can use QueryString to store values in the URL. The value of the query string
can be seen in the URL and is visible to all users.
 Request.QueryString() is used to fetch the query string value.

First.aspx

protected void Button1_Click(object sender, EventArgs e)


{
Response.Redirect("next.aspx?name=" + TextBox1.Text + "&course=" +
TextBox2.Text + "&fees=" + TextBox3.Text);
}

Next.aspx
protected void Page_Load(object sender, EventArgs e)
{
string n = Request.QueryString["name"];
TextBox1.Text = n;
TextBox2.Text = Request.QueryString["course"];
}

2. Server Side State Management


It is another way which ASP.NET provides to store the user's specific information or the
state of the application on the server machine. It completely makes use of server
resources (the server's memory) to store information.
This management technique basically makes use of the following,
a. Session State
b. Application State

a. Session
 Session is a State Management Technique. A Session can store the value on the
Server.
 Session management is a powerful technique used for preserving data over sessions.
 Session is used to store user information and to uniquely identify a user (or a
browser).
 ASP.NET uses a Session ID, which is generated by the server, to keep track of the
status of the current user’s information.
 When a new user submits a request to the server, ASP.NET automatically generates
a Session ID and that Session ID is transmitted with every request and response
made by that particular user.
 A session is one of the best techniques for State Management because it stores the
data as client-based, in other words, the data is stored for every user separately and
the data is secured also because it is on the server.

Program to understand session.


In this program 4 pages are created login, enroll, third and logout page. To access enroll
and third page, user has to login otherwise he wont be able to access that page, so to
track whether user is logged in or not we will use session.

LOGIN PAGE

namespace sessions
{
public partial class sess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

protected void Button1_Click(object sender, EventArgs e)


{

if(TextBox1.Text=="sahyog" && TextBox2.Text=="sahyog123")


{
Session["user"] = TextBox1.Text;
Session["pswd"] = TextBox2.Text;
Response.Redirect("enroll.aspx");
}
else
{
TextBox1.Focus();
}
}
}
}

ENROLL PAGE
namespace sessions
{
public partial class enroll : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Session["user"] ==null)
{
Response.Redirect("Login.aspx");
}
else
{
Label1.Text = "HELLO " + Session["user"];
}
}

protected void Button1_Click(object sender, EventArgs e)


{
Session["course"] = DropDownList1.SelectedItem;
Response.Redirect("third.aspx");
}
}
}

THIRD.ASPX
protected void PREV_Click(object sender, EventArgs e)
{
if(Session["user"]==null || Session["pswd"]==null)
{
Response.Redirect("LOGIN.ASPX");
}
else
{
Response.Redirect("enroll.ASPX");
}
}
protected void LOGOUT_Click(object sender, EventArgs e)
{
Response.Redirect("logout.aspx");
}

LOGOUT.ASPX
namespace sessions
{
public partial class logout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Session["user"]!=null)
{
Session.Abandon();
Response.Redirect("login.aspx");
}

}
}
}

Setting Session Timeout:


 By default asp.net web application manages session for 20 minutes and after 20
minutes session gets destroyed.
 But if user wants to manually set the session timeout,then following line must be
written in web.config file.

<system.web>
<sessionState timeout="1"> </sessionState>
</Sytem.web>

 Here 1 means 1 minute

b. Application State
 ASP.Net Application state is a server side state management technique.
 Application state is a global storage mechanism that used to stored data on the
server and shared for all users, means data stored in Application state is common
for all user. Data from Application state can be accessible anywhere in the
application. Application state is based on the System.Web.HttpApplicationState
class.
 The application state used same way as session state, but session state is specific
for a single user session, where as application state common for all users of
asp.net application.
 Syntax of Application State
Store information in application state

Application[“name”] = “sahyog college”;

Retrieve information from application state

string str = Application[“name”].ToString();

Example of Application State in ASP.Net


 Generally we use application state for calculate how many times a given page has
been visited by various clients.
 Run following code in different browsers to get the output

Set Following code in global.asax file

Global.asax
protected void Session_Start(object sender, EventArgs e)
{
if(Application["c"] != null)
{
Application["c"] = Convert.ToInt32(Application["c"].ToString()) + 1;
}
else
{
Application["c"] = 1;
}
}

Aspx File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace applicationss
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = “Total Visit = ” + Application["c"].ToString();
}
}
}

Output:

ADO.NET:
 ADO.NET stands for ActiveX Data Object.
 It is a module of .Net Framework which is used to establish connection between
application and data sources.
 Data sources can be such as SQL Server and XML.
 ADO.NET consists of classes that can be used to connect, retrieve, insert and delete
data.
 All the ADO.NET classes are located into System.Data.dll and integrated with XML
classes located into System.Xml.dll.
 ADO.NET has two main components that are used for accessing and manipulating
data are the .NET Framework data provider and the DataSet.

Data Provider Model:

 Data provider is used to connect to the database, execute commands and retrieve
the record. It is lightweight component with better performance. It also allows us
to place the data into DataSet to use it further in our application.
 The .NET Framework provides the following data providers that we can use in our
application

.NET Framework data Description


providers

SQL Server It provides data access for Microsoft SQL Server. It requires
the System.Data.SqlClient namespace.

OLEDB It is used to connect with OLE DB. It requires


the System.Data.OleDb namespace.

ODBC It is used to connect to data sources by using ODBC. It


requires the System.Data.Odbc namespace.

Oracle It is used for Oracle data sources. It uses


the System.Data.OracleClient namespace.

Core Objects of data providers:


 Following are the core object of Data Providers.

Object Description

Connection It is used to establish a connection to a specific data source.

Command It is used to execute queries to perform database operations.

DataReader It is used to read data from data source. The DbDataReader is a base class
for all DataReader objects.

DataAdapter It populates a DataSet and resolves updates with the data source. The base
class for all DataAdapter objects is the DbDataAdapter class.

Namespaces for SQL Server Data Access:


1. System.Data.SqlClient:
 It contains SqlConnection and SqlCommand,SqlDataReader & SqlDataAdapter class.
2. System.Data:
 It contains DataSet Class.

Important Classes used while dealing with database

1. SqlConnection:
 It is used to establish an open connection to the SQL Server database. It is a sealed
class so that cannot be inherited.
 SqlConnection class uses SqlDataAdapter and SqlCommand classes together to
increase performance when connecting to a Microsoft SQL Server database.
 Connection does not close explicitly even it goes out of scope. Therefore, you must
explicitly close the connection by calling Close() method.
 To use SqlConnection Class we have use namespace Using System.Data.SqlClient;

SqlConnection Methods

Method Description

Close() It is used to close the connection to the database.

Open() It is used to open a database connection.


2. SqlCommand Class:
 This class is used to store and execute SQL statement for SQL Server database. It is
a sealed class so that cannot be inherited.
 SqlCommand Class accepts 2 argument first the query string and second connection
object or connection string.

Methods:

Method Description

Cancel() It tries to cancel the execution of a SqlCommand.

ExecuteReader() It is used to send the CommandText to the Connection and builds a


SqlDataReader.

ExecuteXmlReader() It is used to send the CommandText to the Connection and builds an


XmlReader object.
ExecuteScalar() It executes the query and returns the first column of the first row in the
result set. Additional columns or rows are ignored.

ExecuteNonQuery(): This method executes a Transact-SQL statement against the


connection and returns the number of rows affected

3. SqlDataReader class:

 SqlDataReader class in C# is used to read data from the SQL Server database in the
most efficient manner.
 It reads data in the forward-only direction. It means once it reads a record, it will
then read the next record; there is no way to go back and read the previous record.

a. SqlDataReader is Connection-Oriented. It means it requires an open or active


connection to the data source while reading the data. The data is available as long
as the connection with the database exists.
b. SqlDataReader is Read-Only. It means it is also not possible to change the data
using SqlDataReader. You also need to open and close the connection explicitly.

SqlDataReader Class Properties in C#:


The SqlDataReader class provides the following properties.
1. Connection: It gets the System.Data.SqlClient.SqlConnection associated with the
System.Data.SqlClient.SqlDataReader.
2. FieldCount: It gets the number of columns in the current row.
3. HasRows: It gets a value that indicates whether the
System.Data.SqlClient.SqlDataReader contains one or more rows.
4. Item[String]: It gets the specified column’s value in its native format, given the column
name.

ADO.NET SqlDataReader Class Methods in C#:


The SqlDataReader class provides the following methods.

1. Close(): It closes the SqlDataReader object.


2. Read(): It Advances the System.Data.SqlClient.SqlDataReader to the next record and
returns true if there are more rows; otherwise, it is false.

Connected and Disconnected Architecture in ADO.NET


 The ADO.NET is one of the Microsoft data access technologies which is used to establish
a connection between the .NET Application (Console, WCF, WPF, Windows, MVC, Web
Form, etc.) and different data sources such as SQL Server, Oracle, MySQL, XML, etc.
 The ADO.NET framework access the data from data sources in two different ways.
 The models are Connection Oriented Data Access Architecture and Disconnected Data
Access Architecture. In this article, I will explain both these architectures in detail with
Examples.

Types of Architecture to Access the Data using ADO.NET:


The Architecture supported by ADO.NET for communicating with data sources is categorized
into two models. They are as follows:
1. Connected Oriented Architecture
2. Disconnected Oriented Architecture
 So, ADO.NET supports both Connection-Oriented Architectures as well as
Disconnection-Oriented Architecture.

 ADO.NET Connection-Oriented Data Access Architecture:

 In the case of Connection Oriented Data Access Architecture, always an open and active
connection is required in between the .NET Application and the database.
 An example is Data Reader and when we are accessing the data from the database, the
Data Reader object requires an active and open connection to access the data, If the
connection is closed then we cannot access the data from the database and in that case,
we will get the runtime error.
 The Connection Oriented Data Access Architecture is always forward only. That means
using this architecture mode, we can only access the data in the forward direction. Once
we read a row, then it will move to the next data row and there is no chance to move back
to the previous row.

 ADO.NET Disconnection-Oriented Data Access Architecture:


 In the case of Disconnection Oriented Data Access Architecture, always an open and
active connection is not required in between the .NET Application and the database.
In this architecture, Connectivity is required only to read the data from the database
and to update the data within the database.
 An example is DataAdapter and DataSet or DataTable classes. Here, using the
DataAdapter object and using an active and open connection, we can retrieve the data
from the database and store the data in a DataSet or DataTable. The DataSets or
DataTables are in-memory objects or you can say they store the data temporarily
within .NET Application. Then whenever required in our .NET Application, we can fetch
the data from the dataset or data table and process the data. Here, we can modify the
data, we can insert new data, can delete the data from within the dataset or data tables.
So, while processing the data within the .NET Application using DataSet or Datatable,
we do not require an active and open connection.

Differences Between Connected-Oriented Architecture and Disconnected-Oriented


Architecture:
Let us see the Differences Between ADO.NET Connected Oriented Architecture and
Disconnected Oriented Architecture.

ADO.NET Connected Oriented Architecture:


1. It is connection-oriented data access architecture. It means always an active and open
connection is required.
2. Using the DataReader object we can implement the Connected Oriented Architecture.
3. Connected Oriented Architecture gives a faster performance.
4. Connected Oriented Architecture can hold the data of a single table only.
5. You can access the data in a forward-only and read-only manner.
6. Using Data Reader, we cannot persist the data in the database.

ADO.NET Disconnected Oriented Architecture:


1. It is disconnection-oriented data access architecture. It means always an active and
open connection is not required.
2. Using DataAdapter and DataSet or Datatable we can implement Dis-Connected
Oriented Architecture.
3. Disconnected Oriented Architecture gives a lower performance.
4. Disconnected Oriented Architecture can hold the data of multiple tables using dataset
and single table data using Datatable.
5. You can access the data in forward and backward directions and you can also modify
the data.
6. Using Data Adapter, we can persist the DataSet or DataTable data into the database.

Program to display data in gridview using disconnected architecture

protected void Page_Load(object sender, EventArgs e)


{
string cs = "data source=DESKTOP-16RE47P\\SQLEXPRESS; initial catalog=
college1;integrated security=true";
SqlConnection conn = new SqlConnection(cs);
String q="select * from student";
SqlCommand cmd=new SqlCommand(q,conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

Program to insert a record


 We have taken 3 textboxes and on submit button click all the 3 data should get
inserted into student table.
 To execute insert query “ExecuteNonQuery()” method has been used.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace database1
{
public partial class DB1 : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
string cs = "data source=DESKTOP-16RE47P\\SQLEXPRESS;initial
catalog=college1;uid=sa;pwd=deepa123";
conn = new SqlConnection(cs);
}
protected void insert_Click1(object sender, EventArgs e)
{
string q = "insert into student values('" + TextBox4.Text + "','" + TextBox1.Text +
"','" + TextBox2.Text + "')";

cmd = new SqlCommand(q, conn);

conn.Open();

cmd.ExecuteNonQuery();

Response.Write("data stored");

Search A Record From Table & Display It

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace database1
{
public partial class DB1 : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
string cs = "data source=DESKTOP-16RE47P\\SQLEXPRESS; initial
catalog=college1; uid=sa;pwd=deepa123";
conn = new SqlConnection(cs);
}

protected void search_Click1(object sender, EventArgs e)


{
String q1 = "select * from student where roll='" + TextBox3.Text + "'";
conn.Open();
cmd = new SqlCommand(q1, conn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();

Response.Write(dr["name"] + " " + dr["course"]);


}
else
{
Response.Write("data not available");
conn.Close();
}} }

Delete A Record:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace database1
{
public partial class DB1 : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
string cs = "data source=DESKTOP-16RE47P\\SQLEXPRESS;initial
catalog=college1;uid=sa;pwd=deepa123";
conn = new SqlConnection(cs);
}
protected void del_Click1(object sender, EventArgs e)
{
String q1 = "select * from student where roll='" + txt_roll.Text + "'";
conn.Open();
cmd = new SqlCommand(q1, conn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
string q = "delete from student where roll=’”txt_roll.Text+”’";

SqlCommand cmd1 = new SqlCommand(q, conn);

cmd1.ExecuteNonQuery();

Response.Write("data deleted”);
}
else
{
Response.Write("data not found to delete”);
}

con.close();

DELETE

Display data in gridview using connected architecture


using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace database1
{
public partial class DB1 : System.Web.UI.Page
{
SqlConnection conn;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
string cs = "data source=DESKTOP-
16RE47P\\SQLEXPRESS;initial catalog=college1;uid=sa;pwd=deepa123";
conn = new SqlConnection(cs);

string s = "select * from student";


SqlCommand md = new SqlCommand(s, conn);
conn.Open();
SqlDataReader dr = md.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
conn.Close();
}
}

Program to display data in dropdownlist.

protected void Page_Load(object sender, EventArgs e)


{
string cs = "data source=DESKTOP-16RE47P\\SQLEXPRESS; initial
catalog=college1;uid=sa;pwd=deepa123";
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select * from student", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "roll";
DropDownList1.DataValueField = "name";
DataBind();
}

Program to display data in listbox.

protected void Page_Load(object sender, EventArgs e)


{
string cs = "data source=DESKTOP-16RE47P\\SQLEXPRESS;initial
catalog=college1;uid=sa;pwd=deepa123";
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select * from student", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

ListBox1.DataSource = ds;
ListBox1.DataTextField = "roll";
ListBox1.DataValueField = "name";

DataBind();
}

Data Source Control


 Using the ASP.NET Data Source controls, you can retrieve data from a database
without writing a line of ADO.NET code.
 Data Source controls work particularly well with List and Rich Data controls.
 One example is SqlDataSource, for which command logic is supplied through
four properties — SelectCommand, InsertCommand, UpdateCommand, and
DeleteCommand — each of which takes a string.

Note that with the SqlDataSource that you can still use parameterized commands
(e.g. ControlParameter, QueryStringParameter, etc.). Also note that many Rich Data
controls have a DataKeyNames and Auto Generate Insert/Delete/Edit Button
properties.

Configuring datasource control and display record in gridview.


 Drag a datasource control from toolbox
 Click on the arrow -> configure database

 Click on new connection, set server name and select database and click on test
connection.
 Again click here and choose college1connectionstring and click on next

Select name of table and column that you want to display and click next
Click on test query and finish

In this way we can configure data source control.


Now set the data source of gridview control.

Output:

In this way we can also display data in any control using sqldatasource control.
The Data Controls:
Data controls play an important role in this purpose. Data controls used to display the
records in the form of reports.
Some of the Data controls are:
1. Detailsview data control
2. GridView data control
3. DataList data control
4. FormView data control

1. GridView data control:


 This control displays the data in tabular form.
 It not only support the editing and deleting of data, it also support sorting and paging
of data.

EDITING,SORTING,UPATING,DELETING GRIDVIEW
Drag a GRIDVIEW and sqldatasource control.
There must a primary key in table to do insertion, updation and deletion.
Configure the datasource same as we configured for formview control.

Select the options that you want to perform.


Output:

Note:

We have applied paging option but I didn’t find that in my output.its because by
default a web page can display 10 records and we have 8 record in our table.
To get paging option set page size of gridview.

We have set page size to 3 it means now 3 records will be displayed in gridview.

Also we have allowed sorting. so if we click on columns it will be sorted.

Change column name of gridview


Solution:
Click on gridview -> edit columns

Select the field that you want to change and set its header text.
2. FormView Control
 This control displays a single record of data at a time like DetailsView control and
supports the editing of record.
 This control requires the use of template to define the rendering of each item.
 Developer can completely customize the appearance of the record.
 We can use data source control to display data in formview.

display data in formview.


Solution:
Step1: drag a formview and datasource control.
Step2: Configure data source control.
Step3: Set data source of formview control.

Step 4 [optional]: Click on auto format to pick different styles.


Output:

Program to allow paging, insert,deletion and updation in table using form view
control.
Note: to perform insertion,deletion,updation there must be a primary key in table.
Solution:
1. Drag formview and datasource control.
2. Configure datasource,select the table having primary key and click on advanced option.

3. Select both the checkboxes ,click ok,then click on next


4. Click test query then finish

5. Set datasource of form view control and run the code.

 On edit button click will get 2 options update and cancel

Here we can only change name and fees.


 On new button click will get 2 options insert and cancel

 On delete click..record will be deleted from the table

Program to allow paging,change column name [header] in form view


control.
Solution:
 Drag formview control and datasource
 Set enabling paging property of control

 To Change column name click on formcontrol.select ItemTemplate and make changes in


column which you want to display on web page.
 ItemTemplate decides how the data will be visible.

 We can also set header,footer template and also we can add controls from toolbox and
modify them inside form view control template.
Output:

3. DetailsView Control
 DetailsView control used to display a single database record of table layout in ASP.Net.
 Means it works with a single data item at a time. DetailsView control used to display
record, insert, update, and delete records from database.

DetailsView Control Syntax :

<asp:DetailsView ID=“DetailsView1“ runat=“server“></asp:DetailsView>

Display data in details view,allow paging,insertion,deletion and updation.


Solution:
Drag a details view and sqldatasource control.
There must a primary key in details to do insertion, updationa nd deletion.
Configure the datasource same as we configured for formview control.
Select all 4 options
Output:

Changing field name/column name in details view.


Solution:
Click on details view then click edit fields
Select the field that you want to change and change its header text and click
ok.

XML:

XML CLASS:

 The System.Xml namespace contains major XML classes.


 This namespace contains many classes to read and write XML documents.
 Here we are going to concentrate on reader and write class.
 These reader and writer classes are used to read and write XML documents.
 These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlWriter,
and XmlTextWriter.

1. XmlReader
2. XmlTextReader
3. XmlWriter
4. XmlTextWriter

Writing/storing data in xml file

1. Add XML File From Solution Explorer


2. Write following code

<?xml version="1.0" encoding="utf-8" ?>


<student>
<record>
<roll>10</roll>
<name>deepa</name>
<course>BCA</course>
</record>

<record>
<roll>1</roll>
<name>priya</name>
<course>MCA</course>
</record>
</student>

3. Add a web form take a gridview and display these 2 records in that.
Write following code in web form

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace xml_programs
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("XMLFile1.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();
}

Output:

1. XMLWRITER CLASS:
 Xmlwriter is a class available in system.xml namespace.
 It is used to write an xml document
Example:
XmlWriter w= XmlWriter.Create
("C:\\Users\\Deepa\\Source\\Repos\\xml_programs\\xml_programs\\demo2.xml");

The XmlWriter class allows you to write XML to a file. This class contains a number of
methods and properties that will do a lot of the work for you. To use this class, you
create a new XmlTextWriter object.

Methods of XmlWriter:

METHOD DESCRIPTION

WriteStartDocument Writes the XML declaration with the version “1.0”.


WriteEndDocument Closes any open elements or attributes.

Close Closes the stream.

WriteDocType Writes the DOCTYPE declaration with the specified name and optional
attributes.

WriteStartElement Writes the specified start tag.

WriteEndElement Closes one element.

WriteFullEndElement Closes one element.

WriteElementString Writes an element containing a string value.

Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
namespace xml_programs
{
public partial class XmlWriterClass : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void save_Click(object sender, EventArgs e)


{
XmlWriter w= XmlWriter.Create
("C:\\Users\\Deepa\\Source\\Repos\\xml_programs\\xml_programs\\demo2.xml");
w.WriteStartDocument();//body
w.WriteStartElement("Students");//root

w.WriteStartElement("Record");//subnode
w.WriteElementString("roll", "10");
w.WriteElementString("name", "neha");
w.WriteElementString("course", "BSCIT");
w.WriteEndElement();

w.WriteStartElement("Record");//subnode
w.WriteElementString("roll", "11");
w.WriteElementString("name", "PRIYA");
w.WriteElementString("course", "BCA");
w.WriteEndElement();

w.WriteEndElement();
w.WriteEndDocument();
w.Close();
Response.Write("data saved");

}
protected void display_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
DataSet ds = new DataSet();
ds.ReadXml("C:\\Users\\Deepa\\Source\\Repos\\xml_programs\\xml_programs\\demo2.
xml");
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}

2. Xmlreader class:
 The XmlReader is a faster and less memory-consuming alternative. It lets you run
through the XML content one element at a time, while allowing you to look at the
value, and then moves on to the next element.

XMLFILE1.XML

<?xml version="1.0" encoding="utf-8" ?>


<student>
<record>
<roll>10</roll>
<name>deepa</name>
<course>BCA</course>
</record>

<record>
<roll>1</roll>
<name>priya</name>
</record>
</student>

WEBFORM2.ASPX:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace xml_programs
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

protected void Button1_Click(object sender, EventArgs e)


{
XmlTextReader xr = new
XmlTextReader(Server.MapPath("XMLFile1.xml"));
while(xr.Read())
{
switch(xr.NodeType)
{
case XmlNodeType.Element:
ListBox1.Items.Add("<" + xr.Name+ ">");break;
case XmlNodeType.Text:
ListBox1.Items.Add(xr.Value); break;
case XmlNodeType.EndElement:
ListBox1.Items.Add("</" + xr.Name + ">");break;
}
}

}
}
}

OUTPUT:

C#:
 C# is pronounced as "C-Sharp". It is an object-oriented programming language provided
by Microsoft that runs on .Net Framework.
 Anders Hejlsberg is known as the founder of C# language.

By the help of C# programming language, we can develop different types of secured


and robust applications:
 Window applications
 Web applications
 Distributed applications
 Web service applications
 Database applications etc.

C# Features:
C# is object oriented programming language. It provides a lot of features that are given
below.
1. Simple
2. Object oriented
3. Type safe
4. Interoperability
5. Scalable and Updateable
6. Component oriented
7. Structured programming language
8. Rich Library
9. Fast speed

Java vs C#:
1) Java is a high level, robust, secured and C# is an object-oriented
object-oriented programming language programming language developed by
developed by Oracle. Microsoft that runs on .Net Framework.

2) Java programming language is designed C# programming language is designed to


to be run on a Java platform, by the help be run on the Common Language
of Java Runtime Environment (JRE). Runtime (CLR).

3) Java type safety is safe. C# type safety is unsafe.

7) Java doesn't support goto statement. C# supports goto statement.

8) Java doesn't support structures and C# supports structures and unions.


unions.

9) Java does not supports for conditional C# supports for conditional compilation.
compilation.

Structure of C# program:
A C# program consists of the following parts −
 Namespace declaration
 A class
 Class methods
 Class attributes
 A Main method
 Statements and Expressions
 Comments

Creating Hello World Program:


using System;

namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

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 HelloWorldApplication namespace contains the class HelloWorld.
 The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods.
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 does when executed.
 The next line /*...*/ is ignored by the compiler and it is put to add comments in the
program.
 The Main method specifies its behavior with the statement Console.WriteLine("Hello
World");
 WriteLine is a method of the Console class defined in the System namespace. This
statement causes the message "Hello, World!" to be displayed on the screen.
 The last line Console.ReadKey(); is for the Users. This makes the program wait for a key
press and it prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.

Constants:
 The constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
 Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal.
 There are also enumeration constants as well.

Defining Constants:
Constants are defined using the const keyword.
Syntax:
const <data_type> <constant_name> = value;

Example:
Const int a=10;

Variables:
Variables are containers for storing data values.
Declaring (Creating) Variables:
To create a variable, you must specify the type and assign it a value:

Syntax:
type variableName = value;

Example:
int a=12;

Data type:
A data type specifies the size and type of variable values. It is important to use the
correct data type for the corresponding variable; to avoid errors, to save time and
memory, but it will also make your code more maintainable and readable. The most
common data types are:
Data Size Description
Type

int 4 bytes -2,147,483,648 to 2,147,483,647

Byte 1 byte 0 to 255


(unsign
ed)

Sbyte 1 byte -128 to 127


(signed)

short 2 byte -32,768 to 32,767

ushort 2 byte 0 to 65,535

unint 4 byte 0 to 4,294,967,295

long 8 bytes -9,223,372,036,854,775,808 to


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

ulong 8 bytes 0 to 18,446,744,073,709,551,615

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7


decimal digits (suffix ‘f’)

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal


digits

bool 1 bit Stores true or false values


char 2 bytes Stores a single character/letter, surrounded by single
quotes

string 2 bytes Stores a sequence of characters, surrounded by double


per quotes
charact
er

DateTi Represe 0:00:00am 1/1/01


me nts date to
and 11:59:59pm 12/31/9999
time

object Base The object types can be assigned values of any other types,
type of value types,
all other reference types, predefined or user-defined types.
types.

Data Types are classified into 2 types:


1. Value type
2. Reference type

1. Value type:
o Value type variables can be assigned a value directly.
o The value types directly contain data.
o Some examples are int, char, and float, which stores numbers, alphabets, and floating
point numbers, respectively.
o When you declare an int type, the system allocates memory to store the value.

2. Reference type:
o Unlike value types, a reference type doesn't store its value directly. Instead, it
stores the address where the value is being stored. In other words, a reference type
contains a pointer to another memory location that holds the data.
o String, object ,class, array, delegates are reference type
For example, consider the following string variable:
 string s = "Hello World!!";
 The following image shows how the system allocates the memory for the above string
variable.
As you can see in the above image, the system selects a random location in
memory (0x803200) for the variable s. The value of a variable s is 0x600000, which
is the memory address of the actual data value. Thus, reference type stores the
address of the location where the actual value is stored instead of the value itself.

Operators:
An operator is a symbol that is used to perform operations on values or variables.

There are following types of operators to perform different types of operations in C#


language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Ternary/Conditional Operator

1. Arithmetic Operator:
 The operators that are used to perform arithmetic operations such as Addition,
subtraction, multiplication etc. are called arithmetic operators.
 The meaning of all the operators along with examples is shown below:

Arithmetic Description Example Result Priority Associativity


operator

+ Used for addition 10 + 20 30 2 Left to Right

- Used for subtraction 50-10 40 2 Left to Right

* Used for multiplication 10 * 20 200 1 Left to Right

/ Used for division and gives quotient 10/5 2 1 Left to Right

% Used to get remainder. It is read as 4%2 0 1 Left to Right


modulus operator or mod

2. Assignment Operator:
 An operator which is used to copy the data or result of an expression into a memory
location (which is identified by a variable name), is called an assignment operator.
 Copying or storing into a memory location is called assigning and hence the name. The
assignment operator is denoted by ‘=’ sign.
 Assignment always happens from right to left.

Syntax (General rule) for assignment:


Variable = expression/value;

For Example:
 a = b; /* Store the value of b into a */
 area = L * B; /* Compute the product and store in variable area */
 pi = 3.1416; /* Store the number 3.1416 using the variable pi */

Normal mistakes during typing the program:


 a == b; /* Error : “==” is relational operator. This can be used only to compare. Not for
copying */
 a = b * 10 /* Error: No semicolon at the end */
 10 + b = c; /*Error: Expression not allowed on LHS of assignment operator

Shorthand assignment operators:


 Shorthand assignment operators such as +=, - =, *=, /= etc., can be used to assign
values. The table below shows shorthand operators, shorthand statements and the
meaning associated with them :
Shorthand Shorthand Meaning Explanation Associativity
operator statement

+= A+=2 A=A+2 Perform A + 2 and store the Right to Left


result in a

-= B-=C B=B-C Perform B - C and store the result Right to Left


in B

*= A*=3 A=A*3 Perform A *3 and store the result Right to Left


in A

/= A/=B A=A/B Perform A / B and store the Right to Left


result in A

%= A%=B A=A%B Perform A %B and store the Right to Left


result in A

3. Increment and Decrement operators:


Increment operator:
 ‘++’ is an increment operator. This is an unary operator. It increments the value of the
operand by one.
 The increment operator is classified into two categories as shown below:
a. Pre-increment
b. Post-increment
a. Pre-increment Operator:
 If the increment operator ++ is placed before (pre) the operand, then the Operator is
called pre-increment.
 As the name indicates, pre-increment means increment before (pre) the operand value
is used. So, the operand value is incremented by 1 first, and then this incremented
value is used.
 Eg: ++a, ++b etc.

b. Post-increment Operator:
 If the increment operator ++ is placed after (post) the operand, then the operator is
called post-increment. As the name indicates, post-increment means increment
 after (post) the operand value is used. So, operand value is used first and then the
operand value is incremented by 1.
 Eg: a++, b++ etc.

Decrement operator:
 ‘--’ is a decrement operator. This is an unary operator. It decrements the value of the
operand by one.
 The decrement operator is classified into two categories as shown below:
a. Pre-decrement
b. Post-decrement

a. Pre-decrement Operator:
 If the decrement operator - - is placed before (pre) the operand, then the Operator is
called pre-decrement.
 As the name indicates, pre-decrement means decrement before (pre) the operand
value is used. So, the operand value is decremented by 1 first, and then this
decremented value is used.
 Eg: --a, --b etc.

a. Post-increment Operator:
 If the decrement operator -- is placed after (post) the operand, then the operator is
called post-decrement.
 As the name indicates, post-decrement means decrement after (post) the operand
value is used. So, operand value is used first and then the operand value is
decremented by 1.
 Eg: a--, b-- etc.

4. Relational operators:
 The relational operators, also called comparison operators, are used to compare two
operands. They are used to find the relationship between two operands and hence are
called relational operators.
 The two operands may be constants, variables or expressions. The relationship
between these two operands results in true or false.
The relational operators and the meaning associated with them are shown in the
following table:

Operator Description Example Priority Associativity

< Less than 10 < 20 1 Left to right

<= Less than or equal 12 <= 18 1 Left to right

> Greater than 15>10 1 Left to right

>= Greater than or equal 15>=3 1 Left to right

== Equal to 10 ==9 2 Left to right

!= Not equal to 5 !=2 2 Left to right

5. Logical Operator:
 As we have logic gates such as AND, OR and NOT whose output is true or false, we also
have logical operators.
 Logical Operators are used to combine 2 more relational expressions.
 After evaluation, expression consisting of logical operators results in either true or
false and hence such expressions are called logical expressions.

a. Logical AND: The result of logical ‘AND’ operator denoted by && is true if and only
if both the operands are evaluated to true. If one of the operands is evaluated to false.
Operand 1 Operand 2 Result
True(1) True(1) True(1)
True(1) False(0) False(0)
False(0) True(1) False(0)
False(0) False(0) False(0)

b. Logical OR: The result of logical ‘OR’ operator denoted by || is true if and only if at
least one of the operands is evaluated to true. If both the operands are evaluated to
false, the result is false.
Operand 1 Operand 2 Result
True(1) True(1) True(1)
True(1) False(0) True(1)
False(0) True(1) True(1)
False(0) False(0) False(0)

c. Logical Not: The logical ‘NOT’ denoted by ! can be true or false. The result is true if the
operand is false and the result is false if the operand is true.

Operand 1 Result
True(1) False(0)
False(0) True(1)

1. Conditional Operator:
 The conditional operator is also known as a ternary operator.
 As conditional operator works on three operands, so it is also known as the ternary
operator.
 It is represented by two symbols, i.e. '?' and ':'.
 The behavior of the conditional operator is similar to the 'if-else' statement.
Syntax1:
Expression1? expression2: expression3;
Syntax2:
Variable=Expression1? expression2: expression3;

Meaning of the above syntax.


 In the above syntax, the expression1 is a Boolean condition that can be either true or
false (Yes/No) value.
 If the expression1 results into a true value, then the expression2 will execute.
 If the expression1 returns false value then the expression3 will execute.
 Bit-wise Operator:
 In arithmetic-logic unit (which is within the CPU), mathematical operations like:
addition, subtraction, multiplication and division are done in bit-level.
 To perform bit-level operations in C programming, bitwise operators are used.
The bit-wise operators and the meaning associated with them are shown in the
following table:
Operator Description Example Priority Associativity
& Bitwise AND. 12 & 15 3 Left to right
| Bitwise OR 5|2 5 Left to right
^ Bitwise XOR 11 ^ 10 4 Left to right
~ Bitwise NOT ~10 1 Left to right
<< Bitwise Left Shift 10<<1 2 Left to right
>> Bitwise Right 12>>1 2 Left to right
Shift

Ternary Operator/Conditional Operator:


C# includes a decision-making operator ?: which is called the conditional operator or
ternary operator. It is the short form of the if else conditions.

Syntax:
condition ? statement 1 : statement 2;

Example:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 20, y = 10;

string result = x > y ? "x is greater than y" : "x is less than y";

Console.WriteLine(result);
}
}
}

TYPE CASTING:
Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
 Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double

 Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char

Implicit Casting:
Implicit casting is done automatically when passing a smaller size type to a larger size
type.

int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9

Explicit Casting:
Explicit casting must be done manually by placing the type in parentheses in front of
the value.

double myDouble = 9.78;


int myInt = (int) myDouble; // Manual casting: double to int

Console.WriteLine(myDouble); // Outputs 9.78


Console.WriteLine(myInt); // Outputs 9
Type Conversion Methods
It is also possible to convert data types explicitly by using built-in methods,
suchas Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int)
and Convert.ToInt64 (long):
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;

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

Conditional Statements/Control Statement:


In C# programming, the control statements are used to test the condition. There are
various types of statements in C#.

i. if statement
ii. if-else statement
iii. nested if statement
iv. if-else-if ladder
v. switch

i. if statement:
The C# if statement tests the condition. It is executed if condition is true.

Syntax:
if(condition)
{
//code to be executed
}
Program:
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
}
}
ii. if- else Statement
Use the else statement to specify a block of code to be executed if the condition is False.

Syntax
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}

Program:
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}

}
}

iii. IF-else-if ladder Statement


The C# if-else-if ladder statement executes one condition from multiple statements.
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
}

Program:
using System;
public class IfExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number to check grade:");
int num = Convert.ToInt32(Console.ReadLine());

if (num <0 || num >100)


{
Console.WriteLine("wrong number");
}
else if(num >= 0 && num < 50){
Console.WriteLine("Fail");
}
else if (num >= 50 && num < 60)
{
Console.WriteLine("D Grade");
}
else if (num >= 60 && num < 70)
{
Console.WriteLine("C Grade");
}
else if (num >= 70 && num < 80)
{
Console.WriteLine("B Grade");
}
else if (num >= 80 && num < 90)
{
Console.WriteLine("A Grade");
}
else if (num >= 90 && num <= 100)
{
Console.WriteLine("A+ Grade");
}
}
}

iv. Switch:
The C# switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C#.
Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......

default:
//code to be executed if all cases are not matched;
break;
}

Program:
using System;
public class SwitchExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

switch (num)
{
case 10: Console.WriteLine("It is 10"); break;
case 20: Console.WriteLine("It is 20"); break;
case 30: Console.WriteLine("It is 30"); break;
default: Console.WriteLine("Not 10, 20 or 30"); break;
}
}
}

Looping Statements:
Looping in a programming language is a way to execute a statement or a set of
statements multiple times depending on the result of the condition to be evaluated to
execute statements. The result condition should be true to execute statements within
loops.

Loops are mainly divided into two categories:

Entry Controlled Loops:


 The loops in which condition to be tested is present in beginning of loop body are
known as Entry Controlled Loops.
 while loop and for loop are entry controlled loops.

1. while loop: The test condition is given in the beginning of the loop and all
statements are executed till the given boolean condition satisfies when the condition
becomes false, the control will be out from the while loop.

Syntax:
Initialization;
while (condition)
{
statements...
incr/decr
}

Program:
using System;

class whileLoopDemo
{
public static void Main()
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
Console.WriteLine("Hello");

// Increment the value of x for


// next iteration
x++;
}
}
}

2. for loop:
 for loop has similar functionality as while loop but with different syntax.
 for loops are preferred when the number of times loop statements are to be executed
is known beforehand.
 The loop variable initialization, condition to be tested, and increment/decrement of
the loop variable is done in one line in for loop

Syntax:
for (initialization; condition; iterator)
{
// body of for loop
}

Program:
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i=1; i<=5; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
}
}

Exit Controlled Loops:


 The loops in which the testing condition is present at the end of loop body are termed
as Exit Controlled Loops.
 do-while is an exit controlled loop.
Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as
the testing condition is present at the end of loop body.

1. do-while loop
do while loop is similar to while loop with the only difference that it checks the
condition after executing the statements, i.e it will execute the loop body one time for
sure because it checks the condition after executing the statements.

Syntax :
do
{
statements..
incr/decr;
}while (condition);

Program:
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i = 1;

do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;

}
}

Jump Statements:
The jump statements in C# are the statements that allow us to move the program
control from one point to another at any particular instance during the execution of the
program.

There are five types of jump statements used in C# as follows:


1. goto
2. break
3. continue
4. return
5. Throw

1. goto: This statement is used to control the transfer of execution to a labeled statement
within a program. The label has to be a valid identifier of C# before or after any
program statement where the control needs to be transferred.

Example:
using System;
namespace ConsoleApplication
{
class ProgEg
{
static void Main(string[] args)
{
Console.WriteLine(" Goto Starts ");
goto g;
Console.WriteLine(" This line gets skipped ");
g:
Console.WriteLine(" This section will be displayed ");

}
}
}
Output:
Goto Starts
This section will be displayed

2. break:
The C# break is used to break loop or switch statement. It breaks the current flow of
the program at the given condition. In case of inner loop, it breaks only inner loop.
Example:
using System;
public class BreakExample
{
public static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
Output:
1
2
3
4

3. continue: This statement is used to skip over the execution part of the loop on a
certain condition. After that, it transfers the control to the beginning of the loop.
Basically, it skips its following statements and continues with the next iteration of the
loop.

Program:
using System;
public class ContinueExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
Console.WriteLine(i);
} } }
Output:11
1
2
3
4
6
7
8
9
10
C# Functions/Methods
 A method is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also known as functions.
 Why use methods? To reuse code: define the code once, and use it many times.
A function consists of the following components:
 Function name: It is a unique name that is used to make Function call.
 Return type: It is used to specify the data type of function return value.
 Body: It is a block that contains executable statements.
 Access specifier: It is used to specify function accessibility in the application.
 Parameters: It is a list of arguments that we can pass to the function during call.

C# Function Syntax
<access-specifier><return-type>FunctionName(<parameters>)
{
// function body
// return statement
}

Access-specifier, parameters and return statement are optional.


 By default access mode is private. Private functions can be accessed in same class but
not in other class.

C# Function: using no parameter and return type


A function that does not return any value specifies void type as a return type. In the
following example, a function is created without return type.

Program:
using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show() // No Parameter
{
Console.WriteLine("This is non parameterized function");
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program p = new Program(); // Creating Object
p.Show(); // Calling Function
}
}
}

C# Function: using parameter but no return type


using System;
namespace FunctionExample
{
class Program
{
// User defined function without return type
public void Show(string message)
{
Console.WriteLine("Hello " + message);
// No return statement
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show("Rahul Kumar"); // Calling Function
}
}
}

Output:
Hello Rahul Kumar

C# Function: using parameter and return type


using System;
namespace FunctionExample
{
class Program
{
// User defined function
public string Show(string message)
{
Console.WriteLine("Inside Show Function");
return message;
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program p = new Program();
string message = p.Show("Rahul Kumar");
Console.WriteLine ("Hello "+message);
}
}
}

Output:
Inside Show Function
Hello Rahul Kumar

Delegates:
 C# delegates are similar to pointers to functions, in C or C++.
 A delegate is a reference type variable that holds the reference to a method. The
reference can be changed at runtime.
There are three steps involved while working with delegates:
1. Declare a delegate
2. Set a target method
3. Invoke a delegate
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A
delegate can refer to a method, which has the same signature as that of the delegate.
For example, consider a delegate −
public delegate int MyDelegate (string s);
The preceding delegate can be used to reference any method that has a
single string parameter and returns an int type variable.
A delegate can be declared using the delegate keyword followed by a function
signature, as shown below:

Delegate Syntax:

[access modifier] delegate [return type] [delegate name]([parameters])

The following declares a delegate named MyDelegate.

Example: Declare a Delegate:


public delegate void MyDelegate(string msg);

After declaring a delegate, we need to set the target method. We can do it by


creating an object of the delegate using the new keyword and passing a method
whose signature matches the delegate signature.

C# Delegate Example
Let's see a simple example of delegate in C# which calls add() and mul() methods.
using System;
delegate int Calculator(int n);//declaring delegate

public class DelegateExample


{
static int number = 100;
public static int add(int n)
{
number = number + n;
return number;
}
public static int mul(int n)
{
number = number * n;
return number;
}
public static int getNumber()
{
return number;
}
public static void Main(string[] args)
{
Calculator c1 = new Calculator(add);//instantiating delegate
Calculator c2 = new Calculator(mul);
c1(20); //calling add method using delegate
Console.WriteLine("After c1 delegate, Number is: " + getNumber());
c2(3); //calling mul method using delegate
Console.WriteLine("After c2 delegate, Number is: " + getNumber());
}
}

Output:
After c1 delegate, Number is: 120
After c2 delegate, Number is: 360

Multicast Delegate in C#?


 A Multicast Delegate in C# is a delegate that holds the references of more than one
function. When we invoke the multicast delegate, then all the functions which are
referenced by the delegate are going to be invoked.
 If you want to call multiple methods using a delegate then all the method signatures
should be the same.
 += Operator is used for adding multiple methods to delegates.
 -= Operator is used for removing methods from the delegates list.

Example for multicast:


using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;

public static int AddNum(int p)


{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances

NumberChanger nc1 = new NumberChanger(AddNum);


NumberChanger nc2 = new NumberChanger(MultNum);

nc1 += nc2;

//calling multicast
nc1(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

Output:
Value of Num: 75
CLASS
 A class is simply a user-defined data type that represents both state and
behavior.
 The state represents the properties and behavior is the action that objects
can perform.
 In other words, we can say that a class is the blueprint/plan/template that
describes the details of an object.
 A class is a blueprint from which the individual objects are created.

1.1Creating a class
Syntax:
class class_Name
{
Access_specifier data_Type MemberName;
Access_specifier return_type fucntionName()
{
}
}

Example:
class student
{
Public int roll;
Public string name;
}

2.0 OBJECTS
 Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
 In other words, object is an entity that has state and behavior. Here, state
means data and behavior means functionality.
 Object is a runtime entity, it is created at runtime.
 Object is an instance of a class. All the members of the class can be accessed
through object.

2.1 CREATING AN OBJECT


Syntax:
ClassName object=new ClassName();
Example:
Student s1=new student();
C# Object and Class Example
Let's see an example of class that has two fields: id and name. It creates instance
of the class, initializes the object and prints the object value.
using System;
namespace hello
{
public class Student
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void Main(string[] args)


{
Student s1 = new Student();//creating an object of Student
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
}

C# Class Example 2: Having Main() in another class

using System;
namespace first
{
public class Student
{
public int id;
public String name;
}
class TestStudent
{
public static void Main(string[] args)
{
Student s1 = new Student();
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
}

NOTE:
 If Id & Name Is Not declared as public Then It Will Not Be Accessible Outside of Class.

C# Class Example 3: Initialize and Display data through method


Let's see another example of C# class where we are initializing and displaying
object through method.

using System;
namespace first
{
class Student
{
int id;
String name;
public void insert(int i, String n)
{
id = i;
name = n;
}
public void display()
{
Console.WriteLine(id + " " + name);
}
}
class TestStudent
{
public static void Main(string[] args)
{
Student s1 = new Student();
Student s2 = new Student();
s1.insert(101, "Ajeet");
s2.insert(102, "Tom");
s1.display();
s2.display();
}
}
}

Interface:
Like a class, Interface can have methods, properties, events, and indexers as its
members. But interfaces will contain only the declaration of the members. The
implementation of the interface’s members will be given by class who implements the
interface implicitly or explicitly.
 Interfaces specify what a class must do and not how.
 Interfaces can’t have private members.
 By default all the members of Interface are public and abstract.
 The interface will always defined with the help of keyword ‘interface‘.
 Interface cannot contain fields because they represent a particular implementation
of data.
 Multiple inheritance is possible with the help of Interfaces but not with classes.

Syntax for Interface Declaration:


interface <interface_name >
{
// declare Events
// declare indexers
// declare methods
// declare properties
}
Syntax for Implementing Interface:
class class_name : interface_name

To declare an interface, use interface keyword. It is used to provide total abstraction.


That means all the members in the interface are declared with the empty body and
are public and abstract by default. A class that implements interface must implement
all the methods declared in the interface.

// C# program to demonstrate working of interface

using System;
interface inter1
{
// method having only declaration
// not definition
void display();
}

// A class that implements interface.


class testClass : inter1
{

// providing the body part of function


public void display()
{
Console.WriteLine("Sudo Placement GeeksforGeeks");
}

// Main Method
public static void Main (String []args)
{

// Creating object
testClass t = new testClass();

// calling method
t.display();
}
}

You might also like