Você está na página 1de 58

ASP.NET is a Microsoft Technology.

ASP stands for Active Server Pages


ASP.NET is a program that runs inside IIS.
IIS (Internet Information Services) is
Microsoft's Internet server.
IIS comes as a free component with
Windows servers.
IIS is also a part of Windows 2000 and XP
Professional.

Client-side technologies

Server-side technologies

HTML, DHTML, JavaScript


ASP (Active Server Pages)

ASP.NET is the next generation of ASP

ASP.NET is the next generation ASP, but


it's not an upgraded version of ASP.
ASP.NET is an entirely new technology for
server-side scripting. ASP.NET is a part of
the Microsoft .NET framework, and a
powerful tool for creating dynamic and
interactive web pages. ASP.NET is a
server side scripting technology that
enables scripts (embedded in web pages)
to be executed by an Internet server

An ASP.NET file is just the same as an HTML file


An ASP.NET file can contain HTML, XML, and
scripts
Scripts in an ASP.NET file are executed on the
server
An ASP.NET file has the file extension ".aspx"

Button code
...

Button

List

List code
...

Text

Text code
...

Browser

ASP.NET

Event handlers

Initialize
Restore Control State
Load Page
Control Events
1. Change Events

Page_Init
Page_Load
Textbox1_Changed

2. Action Events

Button1_Click

Save Control State


Render
Unload Page

Page_Unload

HTML Controls - Traditional HTML tags


Web Server Controls - New ASP.NET tags
Validation Server Controls - For input
validation
Data Control Database binding
Navigation Control Page Navigate
And many more.

Code at Button or

Ideally Label control is


used to place a static,
non clickable (can't fire
onclick event) piece of
text on the page..

Page_load event
Label1.Text = TextBox1.Text;
Label1.Text =Welcome in
asp.net page;

TextBox control is
used to enter data

Code at Button or Page_load

into the form that

event

can be sent to the


web server by
posting the form. And
also convert it into
multiline or password
fields.

Label1.Text = TextBox1.Text;
TextBox1.Text =Welcome in
asp.net page;

Code at Button event


Button control is generally
used to post the form or fire an
event either client side or
server side. When it is
rendered on the page, it is
generally implemented
through

TextBox1.Text
=Welcome in asp.net
page;

The LinkButton control in


ASP.NET is a HyperLink style
Button. The LinkButton looks
like a HyperLink control but
it is a Button which works as
a HyperLink.

Process: Right Click on


Link
Button ->>properties>Postback Url->>set
page->OK
Or
Double click on Link
btn->>code the
followings
Code at link button
Response.Redirect(test.
aspx");

ImageButton control in ASP.NET is just


like a Button control.
The ImageButton control is used to
display a clickable image.
Events of ImageButton are the same as
Button control. You will provide the
image using ImageUrl property of the
ImageButton control.

Coding at Image Button


Int a,b,c;
A=10;
B=34;
C=a+b;
Label1.text=Sum=+c;

Hyperlink control in ASP.NET is


used to link another webpage
when the control is clicked. In
this example we use two
Hyperlink. When we click the
Hyperlink it will redirect
another page. The path of the
web page will be given in
NavigateUrl field.

Coding At Property
<asp:HyperLink
ID="HyperLink1"
runat="server"
NavigateUrl="http://
www.google.co.in">
Google</asp:HyperLi
nk>

The Dropdown List Web


server control enables
users to select from a
single-selection dropdown list box. The
Dropdown List control is
similar to the List Box
Web server control.

Coding At DropDownSeleted
Index Event
If(DropDownList1.SeletedIndex
==0)
{
Label1.Text=Welcome;
Else
Statement1;
}

The ListBox control in


ASP.NET is used to
display a list of items
with scroller. The user
can click on items.
A ListBox control
provides single or
multiple selections of
item using
SelectionMode
property.

Code is same as
dropdownlist

Coding At
listboxSeleted Index
Event
If(Listbox1.SeletedInd
ex==0)
{
Label1.Text=Welcome
;
Else
Statement1;
}

Coding At Checkbox
CheckBox1_CheckedChange
d Event

The Checkbox Web


server controls provide
a way for users to
switch between truefalse or yes-no options.

If (Checkbox1.Checked)
{
Label1.Text=You are
Good;
}
Must set property
autopostback true

CheckBoxList control in
ASP.NET is used to select
or deselect the item.
ChechBoxList is just like a
RadioButtonList control in
HTML. CheckBoxList
control contains
CheckBoxes in a group.

Coding At
CheckBoxListSeleted
Index Event
If(CheckBoxList1.SeletedInde
x==0)
{
Label1.Text=Welcome;
Else
Statement1;
}

Must set property


autopostback true

Code at Radiobutton
Event
RadioButton web server control is
used for select or deselect an item
when all these RadioButtons will be in
a same group.

If(Radiobutton1.Checked)
{
Label1.Text=Male;
}
Must set property
autopostback true
And make a group for
radiobutton

RadioButtonList control
in ASP.NET is used to
select a RadioButton.
You can make any
number of RadioButton
in RadioButtonList

Coding is Same as Checkbox


list control

Image control in
ASP.NET is used for
designing the webpage
and many other
purpose. You can use
image at design time or
at run
time(programmatically

You can choose


Image Control from
the toolbar ->>and
Set the path of
image using imgurl
Property->ok

Image Map control. This


control enables you to
create an image that has
individual regions that
users can click; these
regions are referred to as
hot spots. Each of these
hot spots can be a
separate hyperlink or can
raise a post back event.

<div>
<asp:ImageMap ID="ImageMap1"
runat="server"
ImageUrl="~/images/dog-cat.jpg"
HotSpotMode="PostBack" >
<asp:CircleHotSpot
AlternateText="Dog" Radius="50"
X="120" Y="42"
PostBackValue="Dog"/>
<asp:CircleHotSpot
AlternateText="Cat" Radius="50"
X="70" Y="140"
PostBackValue="Cat"/>
</asp:ImageMap>
</div>

AdRotator is a Rich Web


Control in ASP.NET.
AdRotator control is used
to
make rotating
advertisement in
ASP.NET.It displays the
different different
images in web page
when you refresh the
web page. You can
provide the information
about the images which
is displayed in AdRotator
using XML file or
database.

Coding for AdRotator in XML file


<Advertisements>
<Ad>
<ImageUrl>image1.gif
</ImageUrl>
<NavigateUrl>http://www.googl
e.com
</NavigateUrl>
</Ad>
</Advertisements>
After than rightclick on
adrotator->>
Choose file ->>select them->ok

Code for upload the image


string path = "~/Upload/" +
FileUpload1.FileName;

The FileUpLoad
control enables
you to upload file
to the server. It
displays a text box
control and a
browse button that
allow users to
select a file to
upload to the
server.

FileUpload1.SaveAs(Server.MapPath
(path));
Image1.ImageUrl = path;
Code for upload the file in drive
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(@"D:\temp\"
+FileUpload1.FileName);
Label1.Text = "File Uploaded: " +
FileUpload1.FileName +"
"+System.DateTime.Now.ToLongDat
eString();
} else
{
Label1.Text = "No File
Uploaded.";
}

MultiView control
in ASP.NET acts as
a container for
group of view
controls. You can
see the all view in
a single MultiView
control in a single
web page

<asp:MultiView ID="MultiView1" runat="server">


<asp:View ID="View1" runat="server">
<asp:Image ID="Image1" runat="server"
ImageUrl="~/22.jpg" Height="95px"
Width="152px" />
<br />
<asp:Button ID="Button1" runat="server"
Text="Next Image" OnClick="NextImage"
/>
</asp:View>

</asp:MultiView>
Coding at page_load
if (!Page.IsPostBack)
{
MultiView1.ActiveViewIndex = 0;
}
Coding at button
MultiView1.ActiveViewIndex += 1;

YoucanusethePanelco
ntrolasacontainerforot
hercontrols.Thisispartic
ularlyusefulwhenyouar
ecreatingcontentprogra
mmaticallyandyouneed
awaytoinserttheconte
ntintothepage.

<asp:PanelID="Panel1"runat="se
rver"ScrollBars="Auto"Width="
450"Height="200"Wrap="true"
BackColor="Aqua"Direction="Le
ftToRight">
<p> Write here Text</p>
</panel>

<asp:PlaceHolder
ID="PlaceHolder1"
runat="server"></asp:PlaceHo
lder>
Coding at load event

PlaceHolder Web server


control in ASP.NET is
used to added the
controls at run time.

HyperLink hyperlink1 = new


HyperLink();
hyperlink1.Text = google";
hyperlink1.NavigateUrl =
"http://www.google.co.in/";
PlaceHolder1.Controls.Add(hyperli
nk1);

A data source control interacts with the


data-bound controls and hides the
complex data binding processes. These
are the tools that provide data to the
data bound controls and support
execution of operations like insertions,
deletions, sorting and updates.

GridView Control
Details View
Datalist View
Form view
List view
Repeater Control

The ASP.NET GridView control adding the ability to take advantage


of specific capabilities of ASP.NET data source controls. to
handle simple operations such as paging, sorting, editing or
deleting data, the GridView control can automatically handle
these operations provided its bound data source control
supports these capabilities.

DetailsView Control:->Details View is a data-bound user interface control that


renders a single record at a time from its associated data source, optionally
providing paging buttons to navigate between records.

The DataList control displays data items in a repeating list, and optionally supports
selecting and editing the items. The content and layout of list items in DataList is
defined using templates.

Repeater Control is used to display repeated list of items that are bound to the control
and its same as gridview and datagridview. Repeater control is lightweight and
faster to display data when compared with gridview and datagrid. By using this
control we can display data in custom format but its not possible in gridview or
datagridview and it doesnt support for paging and sorting. .
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate >
<h2>Employee Detail</h2>
<table border ="2" bgcolor="silver" bordercolor="red">
<tr>
<th>Emp Name is :</th>
<th>Emp no. is :</th>
<th>Salary is :</th>
</tr>
</HeaderTemplate>
<ItemTemplate >
<tr><td bgcolor="">
<%#Eval ("ename") %></td>
<td><%#Eval ("empno") %> </td>
<td><%#Eval ("sal") %>
</td>
</tr>
</ItemTemplate>
<FooterTemplate >
</table><h2>By Abc...</h2></FooterTemplate>
</asp:Repeater>

One of the main tasks for every web developer is to check for errors while developing
web pages. According to the server side terminology, this concept is called as
Validation. Prior to ASP.NET, this task was achieved by using JavaScript and
VBScript. JavaScript was commonly used by many developers and the main
disadvantage of this is that developers had to write lot of code. ASP.NET simplified
this task by providing us with built-in WebForm controls.

There are six controls which are available for performing validation. They are
RequiredFieldValidator
CompareValidator
RegularExpressionValidator
RangeValidator
CustomValidator
ValidationSummary

This is one of the important controls used in majority of web applications. If a user fails
to enter the required information on the form then the message given on this
validation control will appear thereby forcing the user to fill up the required
information.

How to use RequiredFieldValidatator:Right click on


Textbox->>Choose properties->>click Control to
Validate->>ok

With the help of this control, you can compare the value of one control with the value of
another control.

How to use Compare Validator:Right click on


Textbox->>Choose properties->>click Control to
Validate->> and Compare Validator->>choose the
textbox->>select type of valie->> and operator->>ok

his control is used to verify the accuracy of strings using special characters. It will check
for the specific pattern which should match with the code. You have to specify a
regular expression

How to use Regular Expression Validator:Right click


on Textbox->>Choose properties->>click on
validation expression->>select any pre-defined
expression->>ok

With the help of this control, you can check whether


users have entered a value within a specific range as
specified. You can specify the range values using
MinimumValue and MaximumValue properties.
How to use Range validator:Right click on Textbox>>Choose properties->>click Control to Validate->>
and give Minimumvalue and maximumvalue ->>choose
type of function ->>ok

The Validation controls that you have seen above are built-in within the .NET Framework.
You have to apply them as such by utilizing its properties in your ASP.NET application.
With the help of CustomValidator control, you can write your own validation rules and
apply them on the appropriate WebForm control.
Process: Right click on CustomValidator->>choose control to validate->>double click on
Custom Validator->> type the followings colde:

This control collects all the values from the ErrorMessage property
and displays them on ASP.NET page. The data will be presented
either by directly on the page or inside a MessageBox.

Right click on Validation->>choose Validation summary


->>true or
Messagebox->>true

ADO.NET provides consistent access to data sources such as SQL


Server and XML, and to data sources exposed through OLE DB and
ODBC. Data-sharing consumer applications can use ADO.NET to connect
to these data sources and retrieve, handle, and update the data
that they contain.

Some common ADO.NET PROVIDER


ADO.NET data providers:
.NET Framework Data Provider
er
(System.Data.SqlClient)
.NET Framework Data Provider
(System.Data.OleDb)
.NET Framework Data Provider
(System.Data.Odbc)
.NET Framework Data Provider
(System.Data.OracleClient)

for SQL Serv


for OLE DB
for ODBC
for Oracle

using System.Data.SqlClient;//namespace for sqlserver


using System.Data;
string q;
SqlConnection con;
SqlDataAdapter adp;
DataSet ds;
q = "select * from emp";
con = new SqlConnection("data source=.\\sqlexpress;initial
catalog=dbemp;integrated security=true");
con.Open();
ds = new DataSet();
adp = new SqlDataAdapter(q, con);
adp.Fill(ds, "emp");
GridView1.DataSource =ds;
GridView1.DataBind();

using System.Data.SqlClient;//namespace for sqlserver


using System.Data;
Using System.Configuration;
string constr =
ConfigurationManager.ConnectionStrings["constr"].ConnectionSt
ring;
void BindGridView()
{
SqlDataAdapter da = new SqlDataAdapter("select *from
country", constr);
DataSet ds = new DataSet();
da.Fill(ds);
GridViewcountry.DataSource =ds;
GridViewcountry.DataBind();
}

using System.Data.SqlClient;
using System.Data;
using System.Configuration;
DataTable dt = new DataTable();
SqlConnection objcon = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionS
trings["conn"].ToString());
SqlDataAdapter objda = new SqlDataAdapter("select * from emp",
objcon);
objda.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}

string q;
SqlCommand cmd;
SqlConnection con;
q = "insert into student(roll,name,marks)
values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')";
con = new SqlConnection("data source=.\\SQLEXPRESS;initial
catalog=dbemp;integrated security=true");
con.Open();
cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
//Label1.Text = "Save data Successfully...";
Response.Write("<script language='javascript'>alert('Saved data in
table:');</script>");

SqlConnection conn = new SqlConnection ("Data Source=.\\sqlexpress;Initial Catalog=dbemp;Integrated


Security=True");
SqlCommand cmd = new SqlCommand ();
cmd.Connection = conn;
string strQuery = "Insert into st1 (id,name,marks) values (@roll,@name,@marks)" ;
cmd.CommandText = strQuery;
cmd.CommandType = CommandType .Text;
//Adding Parameters to the Command Object.
cmd.Parameters.AddWithValue( "@roll", Int32.Parse(TextBox1.Text));
cmd.Parameters.AddWithValue("@name", TextBox2.Text);
cmd.Parameters.AddWithValue("@marks", Int32.Parse(TextBox3.Text));
//Connection Object Open
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Saved data in table:');</script>");

q = "select username,password from login where username='" + TextBox1.Text +


"'and password='" + TextBox2.Text + "'";
con = new SqlConnection("data source=.\\sqlexpress;initial
catalog=user;integrated security=true");
con.Open();
cmd = new SqlCommand(q, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.Redirect("Welcome.aspx");
}
else
{
//Label1.text="plz check username and passowrd";
Response.Redirect("Error.aspx");
}

q = "select ename ,job from emp where empno = " + TextBox1.Text + "";
cn = new SqlConnection("data source = .\\sqlexpress; integrated security = true; initial catalog = dbemp;");
cn.Open();
cmd = new SqlCommand(q, cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
protected void TextBox1_TextChanged(object sender,
{
EventArgs e)
Label3.Visible = true;
{
Label4.Visible = true;
Label2.Visible = false;
TextBox2.Visible = true;
Label3.Visible = false;
TextBox3.Visible = true;
Label4.Visible = false;
TextBox2.Text = dr[0].ToString();
TextBox2.Visible = false;
TextBox3.Visible = false;
TextBox3.Text = dr[1].ToString();
}
}
else
{
Label2.Visible = true;
Label2.Text = "No Such Record Exists";
}

Coding at button :
q = "select * from emp where empno = " + TextBox1.Text + "";
cn = new SqlConnection("data source = .\\sqlexpress; integrated security = true; initial catalog =
dbemp;");
cn.Open();
cmd = new SqlCommand(q, cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
GridView1.Visible = true;
GridView1.DataSource = dr;
GridView1.DataBind();
}
else
{
Coding at Textbox Changed Event
Label2.Visible = true;
Label2.Visible = false;
GridView1.Visible = false;
GridView1.Visible = false;
Label2.Text = "No Such Record Exists";
}

Private void bindgridview()


{
Coding for binding the gridview with help of method
}
Call it page_load event
if (!IsPostBack)
{
bindgridview();
}
Coding at Gridview_PageIndexchangin
GridView1.PageIndex = e.NewPageIndex;
bindgridview();

Coding at button :
private void showdata()
{
String ConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
// DataTable dt = new DataTable();
DataSet dt = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "select * from emp";
cmd.CommandText = "show";//show is stored p name
cmd.Connection = con;
con.Open();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind(); }

Cal it in page_load event


if (!IsPostBack)
{
showdata();
}

Coding at button :
//save data using stored proc
String ConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ins10";//name of stored p
cmd.Parameters.Add("@roll", SqlDbType.Int).Value = TextBox1.Text;
// cmd.Parameters.AddWithValue("@id", TextBox1.Text);
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = TextBox2.Text.Trim();
cmd.Parameters.Add("@marks", SqlDbType.Int).Value = TextBox3.Text.Trim();
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
Label5.Text = "Record inserted successfully";
con.Close();
con.Dispose();

Coding at button :
//save data using stored proc
String ConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = update";//name of stored p
cmd.Parameters.Add("@roll", SqlDbType.Int).Value = TextBox1.Text;
// cmd.Parameters.AddWithValue("@id", TextBox1.Text);
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = TextBox2.Text.Trim();
cmd.Parameters.Add("@marks", SqlDbType.Int).Value = TextBox3.Text.Trim();
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
Label5.Text = "Record updated successfully";
con.Close();
con.Dispose();

Coding at button :
//save data using stored proc
String ConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = deleteprd";//name of stored p
cmd.Parameters.Add("@roll", SqlDbType.Int).Value = TextBox1.Text;
// cmd.Parameters.AddWithValue("@id", TextBox1.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
Label5.Text = "Record deleted successfully";
con.Close();
con.Dispose();

private void bindddl()


{
q = "select empno from emp";
cn = new SqlConnection("data source = .\\sqlexpress; integrated
security = true; initial catalog = dbemp;");
cn.Open();
ds = new DataSet();
ad = new SqlDataAdapter(q, cn);
ad.Fill(ds, "emp");
DropDownList1.DataSource = ds;
// DropDownList1.DataTextField = "ename";//string value
DropDownList1.DataValueField = "empno";//int value
DropDownList1.DataBind();
}

private void bind()


{
q = "select distinct city from police";
cn = new SqlConnection("data source = .\\sqlexpress;
integrated security = true; initial catalog =dbemp;");
cn.Open();
ds = new DataSet();
ad = new SqlDataAdapter(q, cn);
ad.Fill(ds, "police");
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "city";
//DropDownList1.DataValueField = "empno";
DropDownList1.DataBind();
Coding at Button event
}

q = "select * from police where city =


'"+DropDownList1 .SelectedItem .Text +"'";
cn = new SqlConnection("data source =
.\\sqlexpress; integrated security = true;
initial catalog = dbemp;");
cn.Open();
ds = new DataSet();
ad = new SqlDataAdapter(q, cn);
ad.Fill(ds, "police");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

private void bind()


{
q = "select distinct city from police";
cn = new SqlConnection("data source = .\\sqlexpress;
integrated security = true; initial catalog =dbemp;");
cn.Open();
ds = new DataSet();
ad = new SqlDataAdapter(q, cn);
ad.Fill(ds, "police");
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "city";
//DropDownList1.DataValueField = "empno";Coding at Dropdownlist event
q = "select * from police where city =
DropDownList1.DataBind();
'"+DropDownList1 .SelectedItem .Text +"'";
DropDownList1.Items.
cn = new SqlConnection("data source =
Insert(0, "<--Select your Jobs-->");//add.\\sqlexpress;
the Column in
Dropdownlist
integrated
security = true;
initial catalog = dbemp;");
}

cn.Open();
ds = new DataSet();
ad = new SqlDataAdapter(q, cn);
ad.Fill(ds, "police");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();

Você também pode gostar