0% found this document useful (0 votes)
20 views53 pages

Web Tech Unit4

The document introduces HTML Server Controls in ASP.NET, explaining how HTML elements can be treated as server controls by adding the runat="server" attribute. It outlines the advantages of using these controls, such as their HTML-centric object model and ease of migration. Additionally, it provides detailed descriptions of various HTML server controls, including HtmlAnchor, HtmlButton, HtmlForm, and others, along with their properties and sample code.

Uploaded by

kowsalyaproj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views53 pages

Web Tech Unit4

The document introduces HTML Server Controls in ASP.NET, explaining how HTML elements can be treated as server controls by adding the runat="server" attribute. It outlines the advantages of using these controls, such as their HTML-centric object model and ease of migration. Additionally, it provides detailed descriptions of various HTML server controls, including HtmlAnchor, HtmlButton, HtmlForm, and others, along with their properties and sample code.

Uploaded by

kowsalyaproj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Introduction of HTML Server Controls

The HTML elements are considered as text in ASP.NET file. They cannot be referred as server
side code. These controls can be treated as server control by adding runat=”server” attribute.
The id attribute in the element can be added as reference to the control. All the HTML server
controls are written in the <form> tag.

Advantages of using HTML Server Controls:

o The HTML server controls follow the HTML centric object model. It is similar to HTML
o The controls can interact with the Client side scripting
o The migration of the code can be made easy by adding runat=”server attribute
o The abstraction of the HTML tag is similar to the HTML server control
o The controls do not possess any mechanism for identifying capabilities of the client browser

Control List

1) HtmlAnchor control:

The <a> Html element allows the user to create a hyperlink. User can navigate to the page
defined in the link. The Target property is used to display the Web page. The values can
be _blank, _self, _parent, _top. The properties are mentioned below:

Property Description

Id It specifies the unique id for the control

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value used for defining the control activation

HRef It is the URL target of the link

Inner Text It sets or returns the text between the opening and closing tags of
the element

InnerHtml It sets or returns the content between the opening and closing
tags of the element

On Server Click The function to be executed when the link is clicked by the user

Runat It specifies that the control is a server control

Name It is the name of the anchor

Style It is used to set or return the CSS properties applied to the


control

Target It defines the target window to be opened

Tag Name It returns the element tag name

Title It defines the title to displayed by the browser

Visible It is a Boolean value whether control should be visible or not

A sample code for HTML Anchor control is shown below:

<html xmlns=”http://www.w3.org/1999/xhtml” >


<head run at=”server”>
<title></title>
</head>
<body>
<form id=”form1” run at=”server”>
<div>
<a id=”a1” run at=”server”>Visit Gmail</a><br/>
<a id=”a2” run at=”server”>Visit Yahoo</a><br/>
</div>
</form>
</body>
</html>
public partial class _Default: System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
a1.HRef=”http://www.gmail.com”;
a1.Title=”Welcome to Gmail”;
a1.Target=”_blank”;

a2.HRef=”http://www.yahoo.com”;
a2.Title=”Welcome to yahoo”;
a2.Target=”_blank”;
}
}
Output:

2) HtmlButton control:

The Html Button control is defined using the <button> element. The properties are as mentioned
below:

Property Description
Id It defines a unique id for the control

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value for indicating to enable or disable the control

Runat It specifies that the control is a server control

Inner Html It sets or returns the content between the opening and closing tags of the
element

Inner Text It sets or returns the text between the opening and closing tags of the
element

On Server Click The function to be executed when the button is clicked by the user

Style It is used to set or return the CSS properties applied to the control

Tag Name It returns the element tag name

Visible It is a Boolean value whether control should be visible or not

A sample code to demonstrate HTML Button control is:

<html xmlns=”http://www.w3.org/1999/xhtml” >


<head run at=”server”>
<title></title>
<script language=”javascript” type=”text/javascript”>
//<![ CDATA [
function btn1_onclick ()
{
lbl1.innerHTML =”The button clicked is save”;
}
funciton btn2_onclick()
{
lbl1.innerHTML =”The button clicked is display”;
}
//]]>
</script>
</head>
<body>
<form id=”form1” run at=”server”>
<button id=”btn1” run at=”server” onclick =”return btn1_onclick()” >Save Value </button>
<br/>
<button id=”btn2” run at=”server” onclick=”return btn2_onclick()” >Display Value</button>
<br/>
<label id=”lbl” run at=”server”></label>
</form>
</body>
</html>

Output:

3) HtmlForm control:

The Htmlform control is used to control a <form> element. All the

Html server controls are written within the Html form control. User can add only one form
control for a web page. The POST method is the default method of the Html form control. The
properties are mentioned below:
Property Description

Action It contains a URL defining where to send the data in the form submitted

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value for indicating to enable or disable the control

Id It defines a unique id for the control

Enc Type It is mime type used to encode the content of the form

Inner Html It sets or returns the content between the opening and closing tags of the
element

Inner Text It sets or returns the text between the opening and closing tags of the
element

Method The form posts the data to the server.

Name It is the name of the form

Runat It specifies that the control is a server control

Style It is used to set or return the CSS properties applied to the control

Tag Name It returns the element tag name

Target It defines the target window to be opened

Visible It is a Boolean value whether control should be visible or not

A sample code to demonstrate the HTML form control is shown below:


<html xmlns=”http://www.w3.org/1999/xhtml”>
<head run at=”server”>
<title></title>
<script run at=”server”>
void submit ( object sender, EventArgs e)
{
lbl1.InnerHtml = “Name inserted is:”+name.Value;
}
</script>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
Name: <input is=”name” runat=”server” type=”text” /><br/>
<input id=”button1” runat=”server” type=”submit” value=”submit” onserverclick=”submit”
style=”height:26px” />
<label id=”lbl1” runat=”server”></label>
</div>
</form>
</body>
</html>
Output:

4) HtmlGeneric control:

The HtmlGeneric control is used to control elements other than Html server control. The
<body>, <div>, <span> and <p> are used as Html generic control. The properties are as
mentioned below:
Property Description

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value for indicating to enable or disable the control

Id It defines a unique id for the control

Inner Html It sets or returns the content between the opening and closing tags of the
element

Inner Text It sets or returns the text between the opening and closing tags of the
element

Runat It specifies that the control is a server control

Style It is used to set or return the CSS properties applied to the control

Tag Name It returns the element tag name

Visible It is a Boolean value whether control should be visible or not

5) Html Image control:


The Html Image control is used to control <img> element. The <img> element is used to display
an image. The properties are as follows:

Property Description

Align It is used to align images depending on the surrounding elements. The


values that can be assigned are top, middle, bottom, left, right.

Alt It is short description of the image

Attributes It returns the attribute name and value pairs of the element
Border It is the width of the borders around the image

Disabled It is a Boolean value indicating whether the control can be disabled

Height It is the height of the image

Id It defines a unique id for the control

Runat It specifies that the control is a server control

Style It is used to set or return the CSS properties applied to the control

Src It is the URL of the image to be displayed

Tag Name It returns the element tag name

Visible It is a Boolean value whether control should be visible or not

Width It is the width of the image

An example is as mentioned below:

<html xmlns=”http:www.w3.org/1999/xhtml”>
<head run at=”server”>
<title></title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<img id=”img1” runat=”server” />
</div>
</form>
</body>
</html>
public partial class _Default : System.Web.UI.Page
{
protected void Page Load( object sender, Event Args e)
{
img1.Src =”Image\\Desert.jpg”;
img1.Alt = “Desert”;
img1.Height=90;
img1.Width=100;
}
}

Output:

6) Html Input Button control:

The Html Input Button control is used to control <input type=”button”>, <input type=”reset”>
and <input type=”submit”> elements. The properties are as mentioned below:

Property Description

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value indicating whether the control can be disabled

Id It defines a unique id for the control


Name It is the name of the element

On Server Click It is the function name to executed when the button is clicked

Runat It specifies that the control is a server control

Style It is used to set or return the CSS properties applied to the control

Tag Name It returns the element tag name

Visible It is a Boolean value whether control should be visible or not

Type It is the type of element used

Value It is the value of the element

An example is as mentioned below:


<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
<title></title>
<script runat=”server”>
void submit( object sender, Event Args e)
{
p1.InnerHtml =”Course entered is:”+t1.Value;
}
</script>
</head>
<body>
<form is=”form1” run at=”server”>
<div>
Course: <input id=”t1” run at=”server” type=”text” size=”30” />
<br/>
<input type=”submit” run at=”server” value=”submit” on server click=”submit” /><br/>
<p id=”p1” runat=”server”></p>
</div>
</form>
</body>
</html>
Output:

7) Html Input CheckBox control:

The Html Input CheckBox control is used to control as <input type=”checkbox”> element. The
properties are as mentioned below:

Property Description

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value indicating whether the control can be disabled

Checked It is a Boolean value indicating whether the element is to be checked

Id It defines a unique id for the control

Name It is the name of the element

Runat It specifies that the control is a server control

Style It is used to set or return the CSS properties applied to the control

TagName It returns the element tag name


Visible It is a Boolean value whether control should be visible or not

Type It is the type of element used

Value It is the value of the element

8) Html Input File control: The Html Input File control is used to control an
<input type=”file”> element. The properties are as mentioned below:

Property Description

Accept It provides a list of acceptable MIME types

Attributes It returns the attribute name and value pairs of the element
Disabled It is a Boolean value indicating whether the control can be disabled

Id It defines a unique id for the control

Max Length It defines the maximum number of characters allowed in the element

Name It is the name of the element

Posted File It gets access to the posted file

Runat It specifies that the control is a server control

Size It is the width of the element

Style It is used to set or return the CSS properties applied to the control

Tag Name It returns the element tag name

Visible It is a Boolean value whether control should be visible or not

Type It is the type of element used

Value It is the value of the element


9) HtmlInputHidden control: The HtmlInputHidden control is sued to control an <input
type=”hidden”> element. The properties are as mentioned below:

Property Description

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value indicating whether the control can be disabled

Id It defines a unique id for the control

Name It is the name of the element

Runat It specifies that the control is a server control


Style It is used to set or return the CSS properties applied to the control

Tag Name It returns the element tag name

Visible It is a Boolean value whether control should be visible or not

Type It is the type of element used

Value It is the value of the element

10) Html Input Radio Button: The Html Input Radio Button control is used to control an
<input type=”radio”> element. The properties are as mentioned below:
Property Description

Attributes It returns the attribute name and value pairs of the element

Disabled It is a Boolean value indicating whether the control can be disabled

Checked It is a Boolean value indicating whether the element is to be checked

Id It defines a unique id for the control

Name It is the name of the element

Run at C

Style It is used to set or return the CSS properties applied to the control

Tag Name It returns the element tag name

Visible It is a Boolean value whether control should be visible or not

Type It is the type of element used

Value It is the value of the element


Output:

11) HtmlInputText control: The HtmlInputText control is used to control <input type=”text”>
and <input type=”password”> elements. The properties are stated below:
Property Description

Attributes It returns the attribute name and value pairs of the element

Id It defines a unique id for the control

Max Length It defines the maximum characters allowed in the element

Run at It defines a unique id for the control

Size It is the width of the element

Disabled It is a Boolean value indicating whether the control can be disabled


12) Html Select control: The Html Select control is used to control <select> element.
The properties are stated below:

Property Description

Data Member It is the name of the table used

Data Source It is data source in use

Data Text Field It is the data source filed to display the drop down list

Data Value Field It specifies the value selected from the drop down list

Multiple It selects multiple items

Items The list of items in the control

Selected Index It is the index of the selected item

Size The visible items in the control


13) Html Text Area control: The Html Text Area control is used to control <text area>
element. The properties are stated below:

Property Description

Cols It is the number of columns in the control

Attributes It returns the attribute name and value pairs of the element

Value It is the contents of the text area


Name It is unique name of the control

Rows It is the number of rows in the control

An example of the control is shown below:


14) Html Table control: The Html Table control is used to control <table> element.
The properties are stated below:

Property Description

Align It specifies the table alignment

BG Color It is the background color of the table

Border It is width of the borders

Cell Padding It is the space between the cell walls

Cell Spacing It specifies the space between the cell

Height It is the height of the table

Rows It returns the HtmlRowCollection object representing all rows


An example of the control is shown below:
Label Web Server Control:
It is used to display the text in the page. The <asp:Label> tag is used to display the text. An
example of the control is as shown below:
<form id=”form1” runat=”server”>
<div>
<asp:Label ID=”lbl1” runat=”server”></asp:Label><br/>
<asp:Button ID=”Button1” runat=”server” Text=”Button” onclick=”Button1_Click” />
</div>
</form>

protected void Button1_Click ( object sender, EventArgs e )


{
lbl1.Text=”The functionality is correct”;
}

LinkButton Web Server Control:


It is used to button that performs the functionality of a Hyperlink control. The
<asp:LinkButton> tag is used to create the hyperlink button. An example of the LinkButton is
as shown below:
?
<form id=”form1” runat=”server”>
<div>
<asp:LinkButton ID=”LinkButton1” runat=”server” Text=”Show” Font-Size=”Medium”
onclick=”LinkButton1_Click” ></asp:LinkButton><br/>
<asp:Label ID=”lbl2” runat=”server”></asp:Label>
</div>
</form>
protected void LinkButton1_Click ( object sender, EventArgs e)
{
lbl2.Text = “User clicked the link button”;
}
Radio Button Web Server Control:
It is used to create an individual radio button on the page. The <asp:RadioButton> tag is used to
create the control on the page. An example of the control is as shown below:
<body>
<form id=”form1” runat=”server”>
<div>
<asp:RadioButton ID=”RadioButton1” runat=”server” Text=”Male” Checked=”true”
GroupName=”gen” /><br/>
<asp:RadioButton ID=”RadioButton2” runat=”server” Text=”Female” GroupName=”gen”
/><br/>
<asp:Button ID=”Button1” runat=”server” Text=”Show” onclick=”Button1_Click” /><br/>
<asp:Label ID=”Label1” runat=”server” Text=”Label”></asp:Label>
</div>
</form>
</body>

protected void Button1_Click ( object sender, EventArgs e)


{
if ( RadioButton1.Checked)
{
Label1.Text=”Gender selected is male”;
}
else if( RadioButton2.Checked)
{
Label1.Text=”Gender selected is Female”;
}
}
Table Web Server Control:
It declares a table and user can manipulate the control programmatically. The <asp:Table> tag is
used to create the control on the web page. An example of the table control is as shown below:
?
<form id=”form1” runat=”server”>
<div>
<asp:Table ID=”Table1” runat=”server” HorizontalAlign=”Center” CellPadding=”15”
CellSpacing=”0” BorderColor=”Aqua” BorderWidth=”1” >
</asp:Table>
</div>
</form>
protected void Page_Load( object sender, EventArgs e)
{
int nrows = 3;
int ncols = 3;
for ( int j=0; j<nrows; j++)
{
TableRow r = new TableRow();
for ( int i=0; i<ncols;i++)
{
TableCell c = new TableCell();
c.controls.Add( new LiteralControl(“row” + j.ToString()+”, cell”+i.ToString()));
r.cells.Add( c );
}
Table1.Rows.Add( r );
}
}
Text Box Web Server Control:
It is used to create a single line or multi-line text boxes. The <asp:TextBox> tag is used to add
control on the web page. An example of the control is as shown below:
<form id=”form1” runat=”server”>
<div>
<asp:TextBox ID=”TextBox1” runat=”server” BackColor=”Blue” TextMode=”MultiLine”
ontextchanged=”TextBox1_TextChanged”></asp:TextBox><br/>
</div>
</form>

Drop Down List

The Drop Down List control is a web server element that creates the drop-down menu and lets
users select a single item from various options. You can add any number of items to the
Drop Down List.

Almost all web pages contain a drop-down list, but it is mostly present in registration forms or
sign-in pages. A common occurrence is “Select your Location”, where you have to select one
location from various available options.
Syntax

<asp:DropDownList ID=“Sample” runat=“server”>

<asp:ListItem Enabled=”true” Text= “Select Subject” Value= “-1”></asp:ListItem>

<asp:ListItem Text= “History” Value=”1”><asp:ListItem>

<asp:ListItem Text= “Geography” Value=”2”><asp:ListItem>

</asp:DropDownList>

Explanation

The first line sets the ID of the drop-down list used to set the properties of this particular
element, i.e., a DropDownList. The second line to the fourth line describes the items in the list
where an item with value -1 is visible to the user before clicking on it. The DropDownList starts
and ends with a <asp:DropDownList> tag, similar to HTML.

Properties

DropDownList1.Items.Count

The Count() property provides us with the total number of options or items in the drop-down list.

DropDownList1.Items.Add(“ItemName”)

The Add() property lets us add items in the drop-down list by their names.

DropDownList1.Items.Remove(“ItemName”)

The Remove() property lets us remove items from the drop-down list by their names.

DropDownList1.Items.Insert(int index, “ItemName”)

The Insert() property helps us to add new items to the drop-down list at a specific position.

DropDownList1.Items.RemoveAt(int index)
The Remove() property has another form, i.e., when provided with the index (position) of an
item in the drop-down list, it removes the element or the item by its position.

DropDownList1.Items.Clear()

As the name suggests, if we want to replace all the items in the drop-down list or if we want to
clear everything and start afresh, the Clear() property lets us clear the entire drop-down list.

DropDownList1.SelectionItem.Text

This property returns the text of the item selected in the drop-down list and hence is a very
prominent property.

DropDownList1.SelectedIndex

The SelectedIndex property returns the index or the position of the selected item in the drop-
down list. It always starts from 0.

DropDownList1.DataSource

The DataSource property is mainly associated with the Data Table or the Data Set and comes
into action when you need to bind a database or datasheet to the drop-down list.

DropDownList1.DataValueField

The DataValueField property binds the values of the datasheet or database to the drop-down list
which is then visible in the dropdown list.

Item

The Item property provides us with the collection of the items from the drop-down list.

Auto Post Back

The AutoPostBack property comes with two choices, true or false to enable or disable the
automatic postback. The default AutoPostBack value is false. The “true” value indicates that the
server is automatically notified about any changes in user selection of the items from the drop-
down list.

Data Value Field


The DataValueField lets us set the name of the column as a value in the drop-down list. The
DataValueField is not visible to the end-user.

Data Text Field

Unlike the DataValueField, the DataTextField is the text that is visible to the end-user.

For example, DataValueField can be the ID of the employees, stored in the database whereas
DataTextField can be the name of the employees, visible to the user.

Step 1:

Create a new form by specifying its name. Initially, the web form is empty.
Step 2:

Click on the toolbox section on the left and drag a DropDownList item from the menu to the web
form.

Step 3:

To add items to the list, navigate to the properties window and add items to the list. The property
window appears as shown below:

To add items to the list, follow these steps:

Step 1: Click on the Items (Collection) in the properties window. A new window appears that
looks similar to the image below:
Step 2: Add items to the Members section by clicking on the Add button on the left and set its
properties on the right.

Click Ok to finalize and create the required DropDownList.

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;
}
}
}
Files

It is an input controller which is used to upload file to the server. It creates a browse button on the form that pop up a
window to select the file from the local machine.

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

< asp:FileUpload ID="FileUpload1" runat="server"/>

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

<input name="FileUpload1" id="FileUpload1" type="file">

This control has its own properties that are tabled below.

Property Description

Access Key It is used to set keyboard shortcut for the control.

Tab Index The tab order of the control.

Back Color It is used to set background color of the control.

Border Color It is used to set border color of the control.

Border Width It is used to set width of border of the control.

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

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

AllowMultiple It is used to allow upload multiple files by setting true or false.

FileUpload Property Window

Example

Here, we are implementing file upload control in web form.

// 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>
<p>Browse to Upload File</p>
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Upload File" OnClick="Button1_
Click" />
</p>
</form>
<p>
<asp:Label runat="server" ID="FileUploadStatus"></asp:Label>
</p>
</body>
</html>

Code

// 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 System.Web.UI.HtmlControls.HtmlInputFile File1;
protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0)
)
{
string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
string SaveLocation = Server.MapPath("upload") + "\\" + fn;
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
FileUploadStatus.Text = "The file has been uploaded.";
}
catch (Exception ex)
{
FileUploadStatus.Text = "Error: " + ex.Message;
}
}
else
{
FileUploadStatus.Text = "Please select a file to upload.";
}
}
}
}

Create a directory into the project to store uploaded files as we did in below screen shoot.

Output:

Output:

Run the code, it produces following output.


We are uploading a file c# programs.txt.

It displays a successful file uploaded message after uploading as shown in the following screenshot.

The file is stored into upload folder. Look inside the folder, it shows the uploaded file is present.
Download File
ASP.NET provides implicit object Response and its methods to download file from the
server. We can use these methods in our application to add a feature of downloading file
from the server to the local machine.

Here, we are creating an example that allows us to download file.

Download File Example


// Default.aspx

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


CodeBehind="Default.aspx.cs" Inherits="FileDownloadExample._Default" %>
<form id="form1" runat="server">
<p>
Click the button to download a file</p>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Download" /
>
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>
Code
// Default.aspx.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FileDownloadExample
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string filePath = "C:\\Users\\Admi\\Desktop\\abc.txt";
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
// Clear Rsponse reference
Response.Clear();
// Add header by specifying file name
Response.AddHeader("Content-
Disposition", "attachment; filename=" + file.Name);
// Add header for content length
Response.AddHeader("Content-Length", file.Length.ToString());
// Specify content type
Response.ContentType = "text/plain";
// Clearing flush
Response.Flush();
// Transimiting file
Response.TransmitFile(file.FullName);
Response.End();
}
else Label1.Text = "Requested file is not available to download";
}
}
}
Output:
This application will prompt a window to download the file from the server.

DataGrid
.NET Framework provides DataGrid control to display data on the web page. It was introduced
in .NET 1.0 and now has been deprecated. DataGrid is used to display data in scrollable grid. It
requires data source to populate data in the grid.

It is a server side control and can be dragged from the toolbox to the web form. Data Source for
the DataGrid can be either a DataTable or a database. Let's see an example, how can we create a
DataGrid in our application.

This tutorial contains two examples. One is using the DataTable and second is using the database
to display data into the DataGrid.
DataGrid Example with DataTable

This example uses DataTable to bind data to the DataGrid control.

// DataGridExample2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataGridExample2.asp


x.cs" Inherits="DataGridExample.DataGridExample2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>This DataGrid contains DataTable records </p>
<asp:DataGrid ID="DataGrid1" runat="server">
</asp:DataGrid>
</div>
</form>
</body>
</html>
CodeBehind

// DataGridExample2.aspx.cs

using System;
using System.Data;
namespace DataGridExample
{
public partial class DataGridExample2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID");
table.Columns.Add("Name");
table.Columns.Add("Email");
table.Rows.Add("101", "Deepak Kumar", "[email protected]");
table.Rows.Add("102", "John", "[email protected]");
table.Rows.Add("103", "Subramanium Swami", "[email protected]");
table.Rows.Add("104", "Abdul Khan", "[email protected]");
DataGrid1.DataSource = table;
DataGrid1.DataBind();
}
}
}

Output:

It produces the following output to the browser.

DataGrid Example with Database


This example uses database as a data source to display data to the DataGrid. This example includes the following steps.

1) Add a web form

Create a new form to drag DataGrid upon it. See, as we did in the following screenshot.

After adding, now, open toolbox and drag DataGrid control to the form.
After dragging, initially it looks like the following.

This form contains the following source code at backend.

// DataGridExample.aspx

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


CodeBehind="DataGridExample.aspx.cs" Inherits="AdoNetExample.DataGridExample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:DataGrid ID="DataGrid1" runat="server">
</asp:DataGrid>
</form>
</body>
</html>

2) Connect to the Database

In the CodeBehind file, we have code of database connectivity, and binding fetched record to the
DataGrid.

CodeBehind file

// DataGridExample.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetExample
{
public partial class DataGridExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=student; integrate
d security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
DataSet ds = new DataSet();
sde.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
}
}
}
Records in SQL Server Table

A student table contains records that we want to display by using the DataGrid. This table contains the following records.

Output:

After executing this application, it fetches records from the SQL server and displays to the web
browser.

Repeater Controls in ASP.NET

The Repeater control is used to display a repeated list of items that are bound to the control. The
Repeater control may be bound to a database table, an XML file, or another list of items.
Repeater is a Data Bind Control. Data Bind Controls are container controls. Data Binding is the
process of creating a link between the data source and the presentation UI to display the data.
ASP .Net provides rich and wide variety of controls, which can be bound to the data.
Repeater has 5 inline template to format it:
1. <HeaderTemplate>
2. <FooterTemplate>
3. <ItemTemplate>
4. <AlternatingItemTemplate>
5. <SeperatorTemplate>
6. <AlternatingItemTemplate>
HeaderTemplate: This template is used for elements that you want to render once before your
ItemTemplate section.

Footer Template: - This template is used for elements that you want to render once after your
ItemTemplate section.

Item Template: This template is used for elements that are rendered once per row of data. It is
used to display records

Alternating Item Template: This template is used for elements that are rendered every second
row of data. This allows you to alternate background colors. It works on even number of records
only.

Seperator Template: It is used for elements to render between each row, such as line breaks.

Some point about Repeater Control


• It is used to display backend result set. It is used to display multiple tuple.
• It is an unformatted control. The Repeater control is a basic templated data-bound list. It has
no built-in layout or styles, so you must explicitly declare all layout, formatting, and style
tags within the control's templates.
• The Repeater control is the only Web control that allows you to split markup tags across the
templates. To create a table using templates, include the begin table tag (<table>) in the
HeaderTemplate, a single table row tag (<tr>) in the ItemTemplate, and the end table tag
(</table>) in the Footer Template.
• The Repeater control has no built-in selection capabilities or editing support. You can use
the Item Command event to process control events that are raised from the templates to
the control.
We have to use scriptlets for data access.

Data Bind Control can display connected and disconnected model.

Data Bind Control have DataBind() method and DataBound event

-> DataBind()
-> ItemCreated -> Event
-> DataBound -> Event
System.Commom.Data namespace
-> DBDataRecord Class

Controls -> Child Control

Every Data Bind Control implement collection.

The data in Data Source is bound to Repeater using its DataBind Method. Once the data is bound,
the format of each data item is defined by a template like ItemTemplate.
Default.aspx file code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %
>
<!DOCTYPE html PUBLIC "-
//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="Stylesheet" type="text/css" href="StyleSheet.css" />
<title>Repeater Controls in ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="RepeatInformation" runat="server">
<HeaderTemplate>
<table class="tblcolor">
<tr>
<b>
<td>
Roll No
</td>
<td>
Student Name
</td>
<td>
Total Fees
</td>
</b>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="tblrowcolor">
<td>
<%#DataBinder.Eval(Container,"DataItem.RollNo")%>
</td>
<td>
<%#DataBinder.Eval(Container,"DataItem.Name")%>
</td>
<td>
<%#DataBinder.Eval(Container,"DataItem.Fees")%>
</td>
</tr>
</ItemTemplate>
<SeparatorTemplate>
<tr>
<td>
<hr />
</td>
<td>
<hr />
</td>
<td>
<hr />
</td>
</tr>
</SeparatorTemplate>
<AlternatingItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container,"DataItem.RollNo")%>
</td>
<td>
<%#DataBinder.Eval(Container,"DataItem.Name")%>
</td>
<td>
<%#DataBinder.Eval(Container,"DataItem.Fees")%>
</td>
</tr>
</AlternatingItemTemplate>
<SeparatorTemplate>
<tr>
<td>
<hr />
</td>
<td>
<hr />
</td>
<td>
<hr />
</td>
</tr>
</SeparatorTemplate>
<FooterTemplate>
<tr>
<td>
School Records displayed
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page


{
SqlConnection con;
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
cmd.Connection = con;
cmd.CommandText = "select * from student";
con.Open();
RepeatInformation.DataSource = cmd.ExecuteReader();
RepeatInformation.DataBind();
con.Close();
}
}
The output of the above program
Practice Questions:

1. Define Navigator Object Screen.


2. Write <image>tag attributes.
3. Explain User defined Objects.
4. Explain in detail about the Label and Text Control.
5. Explain briefly about Form Objects in HTML.
6. Explain detail about Window Objects.
7. Explain Event Handling and its properties with example.

Additional Resources:
http://www.icwai.org/
http://www.nasbaregistry.org/

Reference:
1. T. A. Powell Complete Reference HTML (Third Edition), TMH, 2002
2. G. Buczek ASP.NET Developers Guide TMH, 2002
3. J. Jaworski Mastering Javascript BPB Publicat ions,19 99

Text Book:
I. Bayross Web Enable Commercial Application Development Using HTML, DHTML ,
Pen CGI, BPB Publications, 2000
2. Deitel & Deitel internet & world wide web How to program, Pearson Education

You might also like