You are on page 1of 71

HTML Server Controls

By default, HTML elements within an ASP.NET file are treated as literal text and are
programmatically inaccessible to page developers. To make these elements programmatically
accessible, you can indicate that an HTML element should be parsed and treated as a server
control by adding a runat="server" attribute.

The unique id attribute allows you to programmatically reference the control. Attributes are
used to declare property arguments and event bindings on server control instances.

HTML server controls must reside within a containing <form> tag with the runat="server"
attribute.

ASP.NET does not require literal (not dynamic) HTML content to be well formed, but it does
require that all HTML elements be properly closed (with either a trailing "/" or a closing tag)
and cleanly nested (overlapping tags are not allowed). If HTML elements are not closed
properly, ASP.NET will not recognize the element. The element will either be ignored or a
compilation error will occur, depending on how the element is formed.

You can create an instance of any Web Forms control in three distinct ways: as an element in
an HTML document, in a Rapid Application Development (RAD) environment that allows
you to drag controls onto a page, or programmatically in a code declaration block or code-
behind file.

In This Section
Shared HTML Control Properties

Describes the properties common to all HTML server controls.

HtmlAnchor Control

Describes the HtmlAnchor control. The HtmlAnchor control allows you to programmatically
access the HTML <a> tag on the server.

HtmlButton Control

Describes the HtmlButton control. The HtmlButton control allows you to programmatically
access the HTML <button> tag on the server.

HtmlForm Control

Describes the HtmlForm control. The HtmlForm control allows you to programmatically
access the HTML <form> tag on the server.

HtmlGenericControl

Describes the HtmlGenericControl control. The HtmlGenericControl class allows you to


programmatically access HTML server control tags that are not represented by a specific .NET
Framework class, such as <span>, <div>, <body>, and <font>.
HtmlImage Control

Describes the HtmlImage control. The HtmlImage control allows you to programmatically
access the HTML <img> tag on the server.

HtmlInputButton Control

Describes the HtmlInputButton control. The HtmlInputButton control allows you to


programmatically access the HTML <input type= button>, <input type= submit>, and <input
type= reset> tags on the server.

HtmlInputCheckBox Control

Describes the HtmlInputCheckBox control. The HtmlInputCheckBox control allows you to


programmatically access the HTML <input type= checkbox> tag on the server.

HtmlInputFile Control

Describes the HtmlInputFile control. The HtmlInputFile control allows you to


programmatically access the HTML <input type= file> tag on the server.

HtmlInputHidden Control

Describes the HtmlInputHidden control. The HtmlInputHidden control allows you to


programmatically access the HTML <input type=hidden> tag on the server.

HtmlInputImage Control
Describes the HtmlInputImage control. The HtmlInputImage control allows you to
programmatically access the HTML <input type= image> tag on the server.

HtmlInputRadioButton Control

Describes the HtmlInputRadioButton control. The HtmlInputRadioButton control allows you


to programmatically access the HTML <input type= radio> tag on the server.

HtmlInputText Control

Describes the HtmlInputText control. The HtmlInputText control allows you to


programmatically access the HTML <input type= text> and <input type= password> tags on
the server.

HtmlSelect Control

Describes the HtmlSelect control. The HtmlSelect control allows you to programmatically
access the HTML <select> tag on the server.

HtmlTable Control

Describes the HtmlTable control. The HtmlTable control allows you to programmatically
access the HTML <table> tag on the server.

HtmlTableCell Control
Describes the HtmlTableCell control. The HtmlTableCell control allows you to
programmatically access the HTML <td> and <th> tags on the server.

HtmlTableRow Control

Describes the HtmlTableRow control. The HtmlTableRow control allows you to


programmatically access the HTML <tr> tag on the server.

HtmlTextArea Control

Describes the HtmlTextArea control. The HtmlTextArea control allows you to


programmatically access the HTML <textarea> tag on the server.

Shared HTML Control Properties


As part of the .NET Framework, ASP.NET, shares inheritance across namespaces and classes.
There are two subsets of HTML controls that share properties from distinct base classes.
These subsets are referred to as container controls and input controls. For more information
about inheritance and class hierarchies, see Web Forms Controls Hierarchy.

Any attribute declared on an HTML control is added to the control's Attribute collection and
can be manipulated programmatically, just like a property. For example, if you declare a
bgcolor attribute on a <body> element, you can programmatically access the attribute and
write event handlers to change its value.

Properties Shared by All HTML Controls


Attributes Gets all attribute name and value pairs expressed on a server control
tag within a selected ASP.NET page.

Note In Html Server controls, manipulating the Attributes collection


is the same as manipulating the ViewState.

HtmlControl.Attributes
Property
Gets a collection of all attribute name and value pairs expressed
on a server control tag within the .aspx file.
[Visual Basic]
Public ReadOnly Property Attributes As
AttributeCollection
[C#]
public AttributeCollection Attributes {get;}
[C++]
public: __property AttributeCollection*
get_Attributes();
[JScript]
public function get Attributes() :
AttributeCollection;
Property Value

A System.Web.UI.AttributeCollection object that contains all


attribute name and value pairs expressed on a server control tag
within the Web page.

Remarks

Use this property to programmatically access the attributes of


the HTML server control. All Html server controls store their
attributes in the Control.ViewState.

HTML attributes are treated by the .NET Framework as


properties on the HTML server control to which they belong.

For additional information on the attributes collection, see the


System.Web.UI.AttributeCollection class.

Example

[Visual Basic, C#, JScript] The following example demonstrates


how to use the Attributes property to determine the attributes of
the HtmlSelect control.

[Visual Basic]
<%@ Page Language="VB" AutoEventWireup="True" %>

<html>

<script language="VB" runat="server">


Sub Page_Load(sender As Object, e As EventArgs)
Message.InnerHtml = "<h4>" & "The select
box's attributes collection contains:" & "</h4>"

Dim keys As IEnumerator =


Select1.Attributes.Keys.GetEnumerator()

While keys.MoveNext()
Dim key As String = CType(keys.Current,
String)
Message.InnerHtml &= key & "=" &
Select1.Attributes(key) & "<br>"
End While
End Sub 'Page_Load

</script>

<body>

<h3>HtmlControl Attribute Collection Example</h3>

Make a selection:

<select id="Select1"
style="font: 12pt verdana;
background-color:yellow;
color:red;"
runat="server">

<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>

</select>

<p>

<span id="Message" MaintainState="false"


runat="server" />

</body>
</html>

[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>

<html>

<script language="C#" runat="server">


void Page_Load(Object sender, EventArgs e)
{
Message.InnerHtml = "<h4>The select box's
attributes collection contains:</h4>";

IEnumerator keys =
Select.Attributes.Keys.GetEnumerator();

while (keys.MoveNext())
{

String key = (String)keys.Current;


Message.InnerHtml += key + "=" +
Select.Attributes[key] + "<br>";
}
}

</script>

<body>

<h3>HtmlControl Attribute Collection Example</h3>

Make a selection:

<select id="Select"
style="font: 12pt verdana;
background-color:yellow;
color:red;"
runat="server">

<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>

</select>

<p>

<span id="Message" MaintainState="false"


runat="server" />

</body>
</html>

[JScript]
<%@ Page Language="JScript" AutoEventWireup="True"
%>

<html>

<script language="jscript" runat="server">


function Page_Load(sender: Object, e:
EventArgs){
Message.InnerHtml = "<h4>The select box's
attributes collection contains:</h4>"

var keys: IEnumerator =


Select1.Attributes.Keys.GetEnumerator()

while(keys.MoveNext()){
var key: String = String(keys.Current)
Message.InnerHtml += key + "=" +
Select1.Attributes(key) + "<br>"
}
}

</script>
<body>

<h3>HtmlControl Attribute Collection Example</h3>

Make a selection:

<select id="Select1"
style="font: 12pt verdana;
background-color:yellow;
color:red;"
runat="server">

<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>

</select>

<p>

<span id="Message" MaintainState="false"


runat="server" />

</body>
</html>

Disabled Gets or sets a value that indicates whether the disabled attribute is
included when an HTML control is rendered on the browser. Including
this attribute makes the control read-only.

Style Gets all cascading style sheet (CSS) properties that are applied to a
specified HTML server control in an .aspx file.

TagName Gets the element name of a tag that contains a runat="server"


attribute.

Visible Gets or sets a value that indicates whether the HTML server control is
displayed on the page.

Properties Shared by All HTML Input Controls

HTML input controls map to the standard HTML input elements. They include a type
attribute that defines the type of input control they render on a Web page.

The HtmlInputText, HtmlInputButton, HtmlInputCheckBox, HtmlInputImage,


HtmlInputHidden, HtmlInputFile, and HtmlInputRadioButton controls share the
following properties.
Name Gets or sets a unique identifier name for the HtmlInputControl.

Value Gets or sets the value associated with an input control.

Note The value associated with a control depends on the context of


the control. For example, in controls that allow you to enter text,
such as the HtmlInputText control, the value is the text entered in
the control. In controls that do not allow you to enter text, such as
the HtmlInputButton control, the value is the caption displayed in the
control. Refer to the specific control for information regarding the
context of the Value property.

Type Gets the type of an HtmlInputControl. For example, if this property is


set to text, the HtmlInputControl is a text box for data entry.

Properties Shared by All HTML Container Controls

HTML container controls map to HTML elements that are required to have an opening and
closing tag, such as the <select>, <a>, <button>, and <form> elements.

The HtmlTableCell, HtmlTable, HtmlTableRow, HtmlButton, HtmlForm, HtmlAnchor,


HtmlGenericControl, HtmlSelect, and HtmlTextArea controls share the following
properties.

InnerHtml Gets or sets the content found between the opening and closing tags
of the specified HTML control. The InnerHtml property does not
automatically convert special characters to HTML entities. For
example, the less than character (<) is not converted to &lt;. This
property is commonly used to imbed HTML elements in the container
control.

InnerText Gets or sets all text between the opening and closing tags of the
specified HTML control. Unlike the InnerHTML property, the
InnerText property automatically converts special characters to
HTML entities. For example, the less than character (<) is converted
to &lt;. This property is commonly used when you want to display
text with special characters, without specifying the HTML entity.

HtmlAnchor Control
Creates a server-side control that maps to the <a> HTML element and allows you link to
another Web page.
<a id="programmaticID"
href="linkurl"
name="bookmarkname"
OnServerClick="onserverclickhandler"
target="linkedcontentframeorwindow"
title="titledisplayedbybrowser"
runat="server" >
linktext
</a>
Remarks

Use the HtmlAnchor control to programmatically control an <a> HTML element. The <a>
HTML element allows you to create a hyperlink that allows you to move to another location
on the page or to another Web page. The HtmlAnchor control must be well formed with an
opening and closing tag. You can specify the caption for the control by placing text between
the opening and closing tags. This server control is commonly used to dynamically modify the
attributes and properties of the <a> element, display hyperlinks from a data source, and
control events to generate HtmlAnchor controls dynamically.

You can specify the location to display the new Web page by using the Target property.
Target values must begin with a letter in the range from a to z (case insensitive), except the
following special values that begin with an underscore: _blank, _self, _parent, and _top.

You can dynamically generate the URL to which you want the HtmlAnchor control to link.
To generate the HRef property dynamically, declare an HtmlAnchor control in an HTML
document. For example:

<a id="anchor1" runat="server">


Note Remember to embed the HtmlAnchor control inside the opening and closing tags of an
HtmlForm control.

Next, write an event handler that assigns a URL to the HRef property of the HtmlControl.

Although the HtmlAnchor control does not directly support binding to a data source, it is
possible to generate hyperlinks from the values of a field in a data source. First bind the data
source to a list control, such as the Repeater. Next declare an HtmlAnchor control inside the
list control. Finally add inline code for the value of the HRef property that uses the Eval
method of the DataBinder class to specify the field to use.

Example

The following example demonstrates how to dynamically associate a URL with an


HtmlAnchor control when the Page_Load event occurs.

VB
Sub Page_Load(sender As Object, e As EventArgs)
anchor1.HRef = "http://www.microsoft.com"
End Sub
[C#]
void Page_Load(object sender, EventArgs e)
{
anchor1.HRef = "http://www.microsoft.com";
}

The following example demonstrates how to include an HtmlAnchor control within a


Repeater control. Data is bound to the Repeater control, while an HtmlAnchor control is
placed in the ItemTemplate that displays the specified field in the data source as a hyperlink.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
<html>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim dt As New DataTable()
Dim dr As DataRow
dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
dt.Columns.Add(New DataColumn("DateTimeValue", GetType(DateTime)))
dt.Columns.Add(New DataColumn("BoolValue", GetType(Boolean)))
dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
Dim i As Integer
For i = 0 To 8
dr = dt.NewRow()
dr(0) = i
dr(1) = "Item " + i.ToString()
dr(2) = DateTime.Now
If i Mod 2 <> 0 Then
dr(3) = True
Else
dr(3) = False
End If
dr(4) = 1.23 *(i + 1)
dt.Rows.Add(dr)
Next i
MyRepeater.DataSource = New DataView(dt)
MyRepeater.DataBind()
End Sub
</script>

<body>
<h3>Data Binding with the HtmlAnchor</h3>
<p>
<form runat=server>
<asp:Repeater id="MyRepeater" runat="server">
<ItemTemplate>
Link for
<a href='<%# DataBinder.Eval(Container, _
"DataItem.StringValue", _
"detailspage.aspx?id={0}") %>'
runat="server">
<%# DataBinder.Eval(Container, "DataItem.StringValue") %>
</a>
<p>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
<html>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("DateTimeValue", typeof(DateTime)));
dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = 0; i < 9; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = DateTime.Now;
dr[3] = (i % 2 != 0) ? true : false;
dr[4] = 1.23 * (i+1);
dt.Rows.Add(dr);
}
MyRepeater.DataSource=new DataView(dt);
MyRepeater.DataBind();
}
</script>

<body>
<h3>Data Binding with the HtmlAnchor</h3>
<p>
<form runat=server>
<asp:Repeater id="MyRepeater" runat="server">
<ItemTemplate>
Link for
<a href='<%# DataBinder.Eval(Container,
"DataItem.StringValue",
"detailspage.aspx?id={0}") %>'
runat="server">
<%# DataBinder.Eval(Container, "DataItem.StringValue") %>
</a>
<p>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
HtmlButton Control
Creates a server-side control that maps to the <button> HTML element and allows you create
push buttons.

<button id="programmaticID"
OnServerClick="onserverclickhandler"
runat="server" >
buttontext, image, or control
</button>
Remarks

Use the HtmlButton control to program against the HTML <button> element. You can
provide custom code for the ServerClick event of the HtmlButton control to specify the
action performed when the control is clicked.

Note The HtmlButton control renders JavaScript to the client browser. The client browser must
have JavaScript enabled for this control to function properly. For more information on client script,
see Client Script in Web Forms Pages.

You can also customize the appearance of the buttons you place in ASP.NET (.aspx) pages.
The HTML 4.0 <button> element enables you to create buttons composed of embedded
HTML elements (and even other Web Forms controls).

Note The <button> element is defined in the HTML 4.0 specification. Therefore, the HtmlButton
control is supported only in Microsoft Internet Explorer version 4.0 and later.

There are a number of ways to modify the appearance of an HtmlButton control. You can
assign style attributes to the button in the opening tag of the control element, include
formatting elements around the text that you insert between the opening and closing tags of
the control, or assign property value changes for the client-side onmouseover and
onmouseout events, to name a few. You can also include images within the button elements
themselves, or even include other Web Forms controls.

To add styles to an HtmlButton control

1. Declare an HtmlButton control on your Web Forms page:


2. <button runat="server"> </button>
3. In the opening tag of the control, include a style attribute and declare the styles that you
want the button to display. For example, the following code in the opening tag defines the
font size and style, background color, border color, height, and width for the control.
4. style="font: 8pt verdana;background-color:lightgreen;border-
color:black;height=30;width:100"

To include DHTML events in an HtmlButton control


1. Declare an HtmlButton control on your Web Forms page:
2. <button runat="server"> </button>
3. In the opening tag of the control, include the DHTML events that you want to occur on the
browser in response to user behaviors. For example, the following code causes the
background color of the control to change to light green when users move the mouse pointer
over the control.
4. mouseover="this.style.backgroundColor='lightgreen'"

To include formatted text, images, or other Web Forms controls in an HtmlButton


control

1. Declare an HtmlButton control on your Web Forms page:


2. <button runat="server"> </button>
3. Declare the text with formatting tags between the opening and closing tags of the control.
For example, include <b>Click Me!</b> between the control's opening and closing tags to
bold the control text.
4. Between the control's opening and closing tags, include the markup for the image or control
that you want to display. For example, include <img src="/images/MyImage.gif"> to
display the MyImage.gif file stored in your application's image directory.

Note See the control syntax for the control you want to include in the HtmlButton control.

Example

The following example shows the procedures presented in this topic. It also includes code for
two simple event handlers that display a message through an instance of an
HtmlGenericControl that is created by a <span> element.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Button1_OnClick(Source As Object, e As EventArgs)
Span1.InnerHtml = "You clicked Button1"
End Sub

Sub Button2_OnClick(Source As Object, e As EventArgs)


Span1.InnerHtml = "You clicked Button2"
End Sub
</script>
</head>

<body>
<h3>HtmlButton Sample</h3>

<form runat="server">
<p>
<button id="Button1"
OnServerClick="Button1_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
runat="server">
<img src="/quickstart/aspplus/images/right4.gif"> Click me!
</button>
&nbsp;With embedded &lt;img&gt; tag
<p>
<p>
<button id=Button2
OnServerClick="Button2_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
onmouseover="this.style.backgroundColor='yellow'"
onmouseout="this.style.backgroundColor='lightgreen'"
runat="server">
Click me too!
</button>
&nbsp;With rollover effect
<p>
<p>
<span id=Span1 runat="server" />
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Button1_OnClick(object Source, EventArgs e)
{
Span1.InnerHtml="You clicked Button1";
}
void Button2_OnClick(object Source, EventArgs e)
{
Span1.InnerHtml="You clicked Button2";
}
</script>
</head>

<body>
<h3>HtmlButton Sample</h3>

<form runat="server">
<p>
<button id="Button1"
OnServerClick="Button1_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
runat="server">
<img src="/quickstart/aspplus/images/right4.gif"> Click me!
</button>
&nbsp;With embedded &lt;img&gt; tag
<p>
<p>
<button id=Button2
OnServerClick="Button2_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
onmouseover="this.style.backgroundColor='yellow'"
onmouseout="this.style.backgroundColor='lightgreen'"
runat="server">
Click me too!
</button>
&nbsp;With rollover effect
<p>
<p>
<span id=Span1 runat="server" />
</form>
</body>
</html>

HtmlButton Control
Creates a server-side control that maps to the <button> HTML element and allows you create
push buttons.

<button id="programmaticID"
OnServerClick="onserverclickhandler"
runat="server" >
buttontext, image, or control
</button>
Remarks

Use the HtmlButton control to program against the HTML <button> element. You can
provide custom code for the ServerClick event of the HtmlButton control to specify the
action performed when the control is clicked.

Note The HtmlButton control renders JavaScript to the client browser. The client browser must
have JavaScript enabled for this control to function properly. For more information on client script,
see Client Script in Web Forms Pages.
You can also customize the appearance of the buttons you place in ASP.NET (.aspx) pages.
The HTML 4.0 <button> element enables you to create buttons composed of embedded
HTML elements (and even other Web Forms controls).

Note The <button> element is defined in the HTML 4.0 specification. Therefore, the HtmlButton
control is supported only in Microsoft Internet Explorer version 4.0 and later.

There are a number of ways to modify the appearance of an HtmlButton control. You can
assign style attributes to the button in the opening tag of the control element, include
formatting elements around the text that you insert between the opening and closing tags of
the control, or assign property value changes for the client-side onmouseover and
onmouseout events, to name a few. You can also include images within the button elements
themselves, or even include other Web Forms controls.

To add styles to an HtmlButton control

1. Declare an HtmlButton control on your Web Forms page:


2. <button runat="server"> </button>
3. In the opening tag of the control, include a style attribute and declare the styles that you
want the button to display. For example, the following code in the opening tag defines the
font size and style, background color, border color, height, and width for the control.
4. style="font: 8pt verdana;background-color:lightgreen;border-
color:black;height=30;width:100"

To include DHTML events in an HtmlButton control

1. Declare an HtmlButton control on your Web Forms page:


2. <button runat="server"> </button>
3. In the opening tag of the control, include the DHTML events that you want to occur on the
browser in response to user behaviors. For example, the following code causes the
background color of the control to change to light green when users move the mouse pointer
over the control.
4. mouseover="this.style.backgroundColor='lightgreen'"

To include formatted text, images, or other Web Forms controls in an HtmlButton


control

1. Declare an HtmlButton control on your Web Forms page:


2. <button runat="server"> </button>
3. Declare the text with formatting tags between the opening and closing tags of the control.
For example, include <b>Click Me!</b> between the control's opening and closing tags to
bold the control text.
4. Between the control's opening and closing tags, include the markup for the image or control
that you want to display. For example, include <img src="/images/MyImage.gif"> to
display the MyImage.gif file stored in your application's image directory.

Note See the control syntax for the control you want to include in the HtmlButton control.
Example

The following example shows the procedures presented in this topic. It also includes code for
two simple event handlers that display a message through an instance of an
HtmlGenericControl that is created by a <span> element.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Button1_OnClick(Source As Object, e As EventArgs)
Span1.InnerHtml = "You clicked Button1"
End Sub

Sub Button2_OnClick(Source As Object, e As EventArgs)


Span1.InnerHtml = "You clicked Button2"
End Sub
</script>
</head>

<body>
<h3>HtmlButton Sample</h3>

<form runat="server">
<p>
<button id="Button1"
OnServerClick="Button1_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
runat="server">
<img src="/quickstart/aspplus/images/right4.gif"> Click me!
</button>
&nbsp;With embedded &lt;img&gt; tag
<p>
<p>
<button id=Button2
OnServerClick="Button2_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
onmouseover="this.style.backgroundColor='yellow'"
onmouseout="this.style.backgroundColor='lightgreen'"
runat="server">
Click me too!
</button>
&nbsp;With rollover effect
<p>
<p>
<span id=Span1 runat="server" />
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Button1_OnClick(object Source, EventArgs e)
{
Span1.InnerHtml="You clicked Button1";
}
void Button2_OnClick(object Source, EventArgs e)
{
Span1.InnerHtml="You clicked Button2";
}
</script>
</head>

<body>
<h3>HtmlButton Sample</h3>

<form runat="server">
<p>
<button id="Button1"
OnServerClick="Button1_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
runat="server">
<img src="/quickstart/aspplus/images/right4.gif"> Click me!
</button>
&nbsp;With embedded &lt;img&gt; tag
<p>
<p>
<button id=Button2
OnServerClick="Button2_OnClick"
style="font: 8pt verdana;
background-color:lightgreen;
border-color:black;
height=30;
width:100"
onmouseover="this.style.backgroundColor='yellow'"
onmouseout="this.style.backgroundColor='lightgreen'"
runat="server">
Click me too!
</button>
&nbsp;With rollover effect
<p>
<p>
<span id=Span1 runat="server" />
</form>
</body>
</html>
HtmlForm Control
Creates a server-side control that maps to the <form> HTML element and allows you to
create a container for elements in a Web page.

<form id="programmaticID"
method=POST | GET
action="srcpageURL"
runat="server" >
Other controls, input forms, and so on.
</form>
Remarks

Use the HtmlForm control to program against the HTML <form> element. To take
advantage of the postback services, all Web Forms controls, whether HTML, Web, pagelet, or
custom, must be nested between well-formed opening and closing tags of the HtmlForm
control. If the tags are not closed properly, ASP.NET will not recognize the element. The
element will either be ignored or a compilation error will occur, depending on how the
element is formed.

Note You cannot include more than one HtmlForm control on a single Web Forms page.

By default, the HtmlForm control's method attribute is set to POST. You can customize the
method attribute to suit your needs, but setting the method attribute to a value other than
GET or POST can break the built-in view state and post back services provided by the Web
Forms.

Note The action attribute is always set to the URL of the page itself. The action attribute cannot be
changed; therefore, you can only post back to the page itself.

Example

The following example shows three HtmlButton controls with a separate OnServerClick
handler for each button. Each of these events causes a post back to the server (the HtmlForm
control is required for any scenario in which a post back occurs). This example also
demonstrates that only one HtmlForm control is allowed on a Web Forms page, including a
form that supports multiple events. If you include more than one HtmlForm control, the
.NET Framework will throw an exception.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Button1_OnClick(Source As Object, e As EventArgs)
Span1.InnerHtml = "You clicked Button1"
End Sub
Sub Button2_OnClick(Source As Object, e As EventArgs)
Span2.InnerHtml = "You clicked Button2"
End Sub

Sub Button3_OnClick(Source As Object, e As EventArgs)


Span3.InnerHtml = "You clicked Button3"
End Sub
</script>
</head>
<body>
<h3>HtmlForm Sample</h3>
<form id="ServerForm" runat="server">
<button id=Button1 runat="server"
OnServerClick="Button1_OnClick">
Button1
</button>
&nbsp;&nbsp;
<span id=Span1 runat="server" />
<p>
<button id=Button2 runat="server"
OnServerClick="Button2_OnClick">
Button2
</button>
&nbsp;&nbsp;
<span id=Span2 runat="server" />
<p>
<button id=Button3 runat="server"
OnServerClick="Button3_OnClick">
Button3
</button>
&nbsp;&nbsp;
<span id=Span3 runat="server" />
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Button1_OnClick(object Source, EventArgs e)
{
Span1.InnerHtml="You clicked Button1";
}
void Button2_OnClick(object Source, EventArgs e)
{
Span2.InnerHtml="You clicked Button2";
}
void Button3_OnClick(object Source, EventArgs e)
{
Span3.InnerHtml="You clicked Button3";
}
</script>
</head>
<body>
<h3>HtmlForm Sample</h3>
<form id="ServerForm" runat="server">
<button id=Button1 runat="server"
OnServerClick="Button1_OnClick">
Button1
</button>
&nbsp;&nbsp;
<span id=Span1 runat="server" />
<p>
<button id=Button2 runat="server"
OnServerClick="Button2_OnClick">
Button2
</button>
&nbsp;&nbsp;
<span id=Span2 runat="server" />
<p>
<button id=Button3 runat="server"
OnServerClick="Button3_OnClick">
Button3
</button>
&nbsp;&nbsp;
<span id=Span3 runat="server" />
</form>
</body>
</html>

HtmlGenericControl

Creates a server-side control that maps to an HTML element not represented by a specific
.NET Framework class, such as <body> and <div>.

<span | body | div | font | others


id="programmaticID"
runat="server" >
Contentbetweentags
</span | body | div | font | others>
Remarks

Created on the server in response to tags that include the runat="server" attribute/value pair
in elements that do not map directly to a specific HTML control. These elements include the
<span>, <body>, <div>, and <font> elements, among others. The control maps the tag name
of the particular element to be used as an HTML control to ASP.NET through the TagName
property. This control inherits functionality from the HtmlContainerControl class, which
allows you to dynamically change inner content of HTML control tags.

You can use a server-side <span> element to display text generated by event-handler code,
whether through user input or from a source you designate in your event handler. You can
also use the Page_Load event to generate text in a span control and HTML style attributes to
format the text when it is displayed in the browser.

To generate text on a page dynamically from user input using the <span> element

1. Declare a server-side span control on the page and assign it an id attribute to allow
programmatic access to the control.
2. <span id="MySpan" runat="server" />
3. Declare an HtmlInputText control and assign it an id attribute to allow programmatic access
to the control.
4. <input type="text" id="myText" runat="server">
5. Declare an HtmlInputButton control and assign it an id attribute to allow programmatic
access to the control. You should also declare an OnServerClick event handler that specifies
the action to perform when the button is clicked.
6. <input type="submit" Value="Click Here!"
7. OnServerClick="SubmitBtn_Click" runat="server">
8. Create event-handler code that manipulates the value entered by the user in the text box to
display it through the span control. This code can be placed anywhere on the page in a code-
behind file.

VB

Sub SubmitBtn_Click(sender As Object, e As EventArgs)


MySpan.InnerHtml = myText.Value
End Sub
[C#]
void SubmitBtn_Click(object sender, EventArgs e)
{
MySpan.InnerHtml = myText.Value;
}
Example

The following example shows how you can generate text to display based on user input in an
HtmlInputText control. The HtmlGenericControl, which is created by declaring the
<span> element on the page, provides the <span> element with access to the InnerHtml
property. This allows you to manipulate the text string assigned to the <span> element.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub SubmitBtn_Click(Source As Object, e As EventArgs)
MySpan.InnerHtml = "Welcome to ASP.NET, " & myText.Value & "."
End Sub
</script>
</head>
<body>
<form id="myForm" runat="server">
<p>Enter your name here:
<input type="text" id="myText" runat="server">
<br><br>
<input type="submit" Value="Click Here!"
OnServerClick="SubmitBtn_Click" runat="server">
<br><br>
<b><span id="MySpan" runat="server"/><b>
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void SubmitBtn_Click(object Source, EventArgs e)
{
MySpan.InnerHtml = "Welcome to ASP.NET, " + myText.Value + ".";
}
</script>
</head>
<body>
<form id="myForm" runat="server">
<p>Enter your name here:
<input type="text" id="myText" runat="server">
<br><br>
<input type="submit" Value="Click Here!"
OnServerClick="SubmitBtn_Click" runat="server">
<br><br>
<b><span id="MySpan" runat="server"/><b>
</form>
</body>
</html>

The following example shows how you can use an HtmlGenericControl to allow a user to
modify a page's background color. It also shows how to use the AttributeCollection class to
programmatically access the attributes that can be declared on any HTML control.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub SubmitBtn_Click(Source As Object, e As EventArgs)
Body.Attributes("bgcolor") = ColorSelect.Value
End Sub
</script>
</head>

<body id=Body runat="server">

<h3>Updating Styles with the HtmlGenericControl</h3>

<form runat="server">
<p>
Select a background color for the page: <p>
<select id="ColorSelect" runat="server">
<option>White</option>
<option>Wheat</option>
<option>Gainsboro</option>
<option>LemonChiffon</option>
</select>
<input type="submit" runat="server"
Value="Apply" OnServerClick="SubmitBtn_Click">
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void SubmitBtn_Click(object Source, EventArgs e)
{
Body.Attributes["bgcolor"] = ColorSelect.Value;
}
</script>
</head>

<body id=Body runat="server">

<h3>Updating Styles with the HtmlGenericControl</h3>

<form runat="server">
<p>
Select a background color for the page: <p>
<select id="ColorSelect" runat="server">
<option>White</option>
<option>Wheat</option>
<option>Gainsboro</option>
<option>LemonChiffon</option>
</select>
<input type="submit" runat="server"
Value="Apply" OnServerClick="SubmitBtn_Click">
</form>
</body>
</html>

HtmlImage Control
Creates a server-side control that maps to the <img> HTML element and allows you to
display an image.

<img id="programmaticID"
alt="alttext"
align= top | middle | bottom | left | right
border="borderwidth"
height="imageheight"
src="imageURL"
width="imagewidth"
runat="server" >
Remarks

Use the HtmlImage control to program against the HTML <img> element. This control
allows you to dynamically set and retrieve the image's source, width, height, border width,
alternate text, and alignment by using the Src, Width, Height, Border, Alt, and Align
properties, respectively.

Note This control does not require a closing tag.

Example

The following example shows how to change a displayed image, based on user choices. It
specifies the /images directory as the source path for the images to display. The value
selected in the HtmlSelect control in the Web Forms page determines which image to display
from the /images directory.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub SubmitBtn_Click(Sender As Object, e As EventArgs)
Image1.Src = "/images/" & Select1.Value
End Sub
</script>
</head>

<body>
<h3>HtmlImage Sample</h3>
<form runat="server">
<img ID="Image1" src="/images/cereal1.gif" runat="server"/>
<p>
<p>
Select an image file to display:
<select id="Select1" runat="server">
<option Value="Cereal1.gif">Healthy Grains</option>
<option Value="Cereal2.gif">Corn Flake Cereal</option>
<option Value="Cereal3.gif">U.F.O.S</option>
<option Value="Cereal4.gif">Oatey O's</option>
<option Value="Cereal5.gif">Strike</option>
<option Value="Cereal7.gif">Fruity Pops</option>
</select>
<p>
<p>
<input type="submit" runat="server" Value="Apply"
OnServerClick="SubmitBtn_Click">
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void SubmitBtn_Click(Object Sender, EventArgs e)
{
Image1.Src="/images/" + Select1.Value;
}
</script>
</head>

<body>
<h3>HtmlImage Sample</h3>
<form runat="server">
<img ID="Image1" src="/images/cereal1.gif" runat="server"/>
<p>
<p>
Select an image file to display:
<select id="Select1" runat="server">
<option Value="Cereal1.gif">Healthy Grains</option>
<option Value="Cereal2.gif">Corn Flake Cereal</option>
<option Value="Cereal3.gif">U.F.O.S</option>
<option Value="Cereal4.gif">Oatey O's</option>
<option Value="Cereal5.gif">Strike</option>
<option Value="Cereal7.gif">Fruity Pops</option>
</select>
<p>
<p>
<input type="submit" runat="server" Value="Apply"
OnServerClick="SubmitBtn_Click">
</form>
</body>
</html>

HtmlInputButton Control

Creates a server-side control that maps to the <input type=button>, <input type=submit>,
and <input type=reset> HTML elements and allows you to create a command button, submit
button, or reset button, respectively.

<input type=button | submit | reset


id="programmaticID"
OnServerClick="onserverclickhandler"
runat="server" >
Remarks

Use the HtmlInputButton control to program against the <input type=button>, <input
type=submit>, and <input type=reset> HTML elements. When a user clicks an
HtmlInputButton control, input from the form that the control is embedded on is posted to
the server and processed. A response is then sent back to the requesting browser.

By providing a custom event handler for the ServerClick event, you can perform a specific set
of instructions when the control is clicked.

Note A reset button does not support the ServerClick event. When a reset button is clicked, all
input controls on the page are not necessarily cleared. Instead, they are returned to their original
state when the page was loaded. For example, if a text box originally contained the value "JohnDoe",
clicking on the reset button would return the text box to this value.

When used in conjunction with the HtmlInputText and HtmlTextArea controls, you can
create user input or authentication pages that can be processed on the server.

Note This control does not require a closing tag.

Example

The following example demonstrates how to use an HtmlInputButton control to submit a


form to the server for processing.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>

<html>

<head>

<script runat="server">

Protected Sub AddButton_Click(sender As Object, e As EventArgs)

Dim Answer As Integer

Answer = Convert.ToInt32(Value1.Value) +
Convert.ToInt32(Value2.Value)

AnswerMessage.InnerHtml = Answer.ToString()

End Sub

</script>

</head>

<body>
<form runat="server">

<h3> HtmlInputButton Example </h3>

<table>

<tr>

<td colspan="5">

Enter integer values into the text boxes. <br>


Click the Add button to add the two values. <br>
Click the Reset button to reset the text boxes.

</td>

</tr>

<tr>

<td colspan="5">

&nbsp;

</td>

</tr>

<tr align="center">

<td>

<input ID="Value1"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>

</td>

<td>

</td>

<td>

<input ID="Value2"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>
</td>

<td>

</td>

<td>

<span ID="AnswerMessage"
runat="server"/>

</td>

</tr>

<tr>

<td colspan="2">

<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="Value1"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value1MinCompareValidator"
ControlToValidate="Value1"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value1MaxCompareValidator"
ControlToValidate="Value1"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>

<td colspan="2">

<asp:RequiredFieldValidator
ID="Value2RequiredValidator"
ControlToValidate="Value2"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MinCompareValidator"
ControlToValidate="Value2"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MaxCompareValidator"
ControlToValidate="Value2"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>

<td>

&nbsp

</td

</tr>

<tr align="center">

<td colspan="4">

<input Type="Submit"
Name="AddButton
Value="Add"
OnServerClick="AddButton_Click"
runat="server"/>

&nbsp;&nbsp;&nbsp;

<input Type="Reset"
Name="AddButton
Value="Reset"
runat="server"/>

</td>

<td>
&nbsp;

</td>

</tr>

</table>

</form>

</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>

<html>

<head>

<script runat="server">

protected void AddButton_Click(Object sender, EventArgs e)


{
int Answer;

Answer = Convert.ToInt32(Value1.Value) +
Convert.ToInt32(Value2.Value);

AnswerMessage.InnerHtml = Answer.ToString();

</script>

</head>

<body>

<form runat="server">

<h3> HtmlInputButton Example </h3>

<table>

<tr>

<td colspan="5">

Enter integer values into the text boxes. <br>


Click the Add button to add the two values. <br>
Click the Reset button to reset the text boxes.

</td>

</tr>

<tr>
<td colspan="5">

&nbsp;

</td>

</tr>

<tr align="center">

<td>

<input ID="Value1"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>

</td>

<td>

</td>

<td>

<input ID="Value2"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>

</td>

<td>

</td>

<td>

<span ID="AnswerMessage"
runat="server"/>

</td>

</tr>

<tr>

<td colspan="2">
<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="Value1"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value1MinCompareValidator"
ControlToValidate="Value1"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value1MaxCompareValidator"
ControlToValidate="Value1"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>

<td colspan="2">

<asp:RequiredFieldValidator
ID="Value2RequiredValidator"
ControlToValidate="Value2"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MinCompareValidator"
ControlToValidate="Value2"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MaxCompareValidator"
ControlToValidate="Value2"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>

<td>

&nbsp

</td

</tr>

<tr align="center">

<td colspan="4">

<input Type="Submit"
Name="AddButton
Value="Add"
OnServerClick="AddButton_Click"
runat="server"/>

&nbsp;&nbsp;&nbsp;

<input Type="Reset"
Name="AddButton
Value="Reset"
runat="server"/>

</td>

<td>

&nbsp;

</td>

</tr>

</table>

</form>

</body>
</html>

HtmlInputCheckBox Control
Creates a server-side control that maps to the <input type=checkbox> HTML element and
allows you to a create check box control that lets the user select a true or false state.

<input type=checkbox
id="programmaticID"
checked
runat="server" >
Remarks

Use the HtmlInputCheckBox control to program against the <input type=checkbox>


HTML element. The HtmlInputCheckBox control does not post back to the server when it is
clicked. The state of the check box is sent to the server for processing when you use a control
that posts back the server, such as the HtmlInputButton control. To determine whether the
check box is selected, test the Checked property of the control.

Note This control does not require a closing tag.

Example

The following example demonstrates how to create an HtmlInputCheckBox control that


allows the user to select a true or false state. When a user clicks the input button included on
the page, the Button1_Click event handler determines whether the HtmlInputCheckBox
control is checked. It then displays a message in a <span> control. Note that even though the
checked value is set to true by default in this example, the user still needs to click Button1 to
display the text.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Button1_Click(Source As Object, e As EventArgs)
If Check1.Checked = True Then
Span1.InnerHtml = "Check1 is checked!"
Else
Span1.InnerHtml = "Check1 is not checked!"
End If
End Sub
</script>
</head>
<body>

<h3>HtmlInputCheckBox Sample</h3>

<form runat="server">
<input id="Check1" type=checkbox runat="server" checked/>
CheckBox1 &nbsp;&nbsp;
<span id=Span1 style="color:red" runat="server" />
<p>
<input type=button id="Button1" value="Enter"
OnServerClick="Button1_Click" runat="server"/>
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Button1_Click(object Source, EventArgs e)
{
if (Check1.Checked == true)
{
Span1.InnerHtml = "Check1 is checked!";
}
else
{
Span1.InnerHtml = "Check1 is not checked!";
}
}
</script>
</head>
<body>

<h3>HtmlInputCheckBox Sample</h3>

<form runat="server">
<input id="Check1" type=checkbox runat="server" checked/>
CheckBox1 &nbsp;&nbsp;
<span id=Span1 style="color:red" runat="server" />
<p>
<input type=button id="Button1" value="Enter"
OnServerClick="Button1_Click" runat="server"/>
</form>
</body>
</html>

HtmlInputFile Control
Creates a server-side control that maps to the <input type=file> HTML element and allows
you to upload a file to the server.

<input type=file
id="programmaticID"
accept="MIMEencodings"
maxlength="maxfilepathlength"
size="widthoffilepathtextbox"
postedfile="uploadedfile"
runat="server" >
Remarks

Use the HtmlInputFile control to program against the HTML <input type=file> element.
You can use the HtmlInputFile control to easily design a page that allows users to upload
binary or text files from a browser to a directory that you designate on your Web server. File
upload is enabled in all HTML 3.2 and later Web browsers.

Example

The following example demonstrates a simple file upload scenario. The first section of code
defines the event handler for the page. When the user clicks the Upload button on the form,
the file name, content length, and amount of content (in bytes), are displayed on the page,
while the file itself is uploaded to the UploadedFiles directory on the server.

Note You must set the enctype attribute of the form to "multipart/form-data".

The code for the form implements an HtmlForm control, an HtmlInputFile control, an
HtmlInputButton control, and four HtmlGenericControls (the <div> element and the three
<span> elements, each with runat="server" attribute/value pairs in their opening tags).

Note To view the information about the uploaded file on the page, the Visible property, which the
HtmlGenericControl inherits from the Control class, must be set to true in the event-handler code.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<script runat="server">
Sub UploadBtn_Click(Sender as Object, e as EventArgs)

' Display information about posted file


FileName.InnerHtml = MyFile.PostedFile.FileName
MyContentType.InnerHtml = MyFile.PostedFile.ContentType
ContentLength.InnerHtml = cStr(MyFile.PostedFile.ContentLength)
FileDetails.Visible = True

' Save uploaded file to server


MyFile.PostedFile.SaveAs("c:\Uploadedfiles\uploadfile.txt")
End Sub
</script>
<body>
<form action="fileupload.aspx"
method="post"
enctype="multipart/form-data"
runat="server">

<h1>ASP.NET File Upload Example</h1>


Select File To Upload to Server:
<input id="MyFile"
type="file"
runat="server">
<br><br>
<input type=submit
value="Upload!"
OnServerclick="UploadBtn_Click"
runat="server">
<br><br><br>
<div id="FileDetails"
Visible=false
runat="server">
FileName: <span id="FileName" runat="server"/> <br>
ContentType: <span id="MyContentType" runat="server"/> <br>
ContentLength: <span id="ContentLength" runat="server"/>bytes
<br>
</div>
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<script runat="server">
void UploadBtn_Click(Object sender, EventArgs e)
{
// Display information about posted file
FileName.InnerHtml = MyFile.PostedFile.FileName;
MyContentType.InnerHtml = MyFile.PostedFile.ContentType;
ContentLength.InnerHtml =
MyFile.PostedFile.ContentLength.ToString();
FileDetails.Visible = true;

// Save uploaded file to server


MyFile.PostedFile.SaveAs("c:\\Uploadedfiles\\uploadfile.txt");
}
</script>
<body>
<form action="fileupload.aspx"
method="post"
enctype="multipart/form-data"
runat="server">

<h1>ASP.NET File Upload Example</h1>


Select File To Upload to Server:
<input id="MyFile"
type="file"
runat="server">
<br><br>
<input type=submit
value="Upload!"
OnServerclick="UploadBtn_Click"
runat="server">
<br><br><br>
<div id="FileDetails"
Visible=false
runat="server">
FileName: <span id="FileName" runat="server"/> <br>
ContentType: <span id="MyContentType" runat="server"/> <br>
ContentLength: <span id="ContentLength" runat="server"/>bytes
<br>
</div>
</form>
</body>
</html>

HtmlInputHidden Control

Creates a server-side control that maps to the <input type=hidden> HTML element and
allows you to store information in a nonviewable control on the form.

<input type="hidden"
id="programmaticID"
value="contentsofhiddenfield"
runat="server" >
Remarks

Use the HtmlInputHidden control to program against the <input type=hidden> HTML
element. Although this control is part of the form, it is never displayed on the form. Since
state is not persisted in HTML, this control is commonly used in conjunction with the
HtmlInputButton and HtmlInputText controls to store information between posts to the
server.

Note This control does not require a closing tag.

Example

The following example demonstrates how to save view-state information across requests
using the HtmlInputHidden control. The <span> control displays the text stored in the
hidden field from the Web request immediately preceding the present request.

There are two event handlers. The first event occurs when the page is posted back to the
server. The event handler takes the text stored in the hidden field from the previous post
request and displays it in a <span> control. The second event occurs when the submit button
is clicked. The event handler takes the contents of the text box and stores it in the hidden field
on the Web page.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Page_Load(Source As Object, e As EventArgs)
If Page.IsPostBack Then
Span1.InnerHtml = "Hidden value: <b>" + HiddenValue.Value +
"</b>"
End If
End Sub

Sub SubmitBtn_Click(Source As Object, e As EventArgs)


HiddenValue.Value = StringContents.Value
End Sub
</script>
</head>

<body>
<h3>HtmlInputHidden Sample</h3>
<form runat="server">
<input id="HiddenValue"
type=hidden value="Initial Value" runat="server">
Enter a string:
<input id="StringContents" type=text size=40 runat="server">
<p>
<input type=submit value="Enter"
OnServerClick="SubmitBtn_Click" runat="server">
<p>
<span id=Span1 runat="server">
This label will display the previously entered text.
</span>
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Page_Load(object Source, EventArgs e)
{
if (Page.IsPostBack)
{
Span1.InnerHtml="Hidden value: <b>" +
HiddenValue.Value + "</b>";
}
}
void SubmitBtn_Click(object Source, EventArgs e)
{
HiddenValue.Value=StringContents.Value;
}
</script>
</head>

<body>
<h3>HtmlInputHidden Sample</h3>
<form runat="server">
<input id="HiddenValue"
type=hidden value="Initial Value" runat="server">
Enter a string:
<input id="StringContents" type=text size=40 runat="server">
<p>
<input type=submit value="Enter"
OnServerClick="SubmitBtn_Click" runat="server">
<p>
<span id=Span1 runat="server">
This label will display the previously entered text.
</span>
</form>
</body>
</html>

HtmlInputImage Control
Creates a server-side control that maps to the <input type=image> HTML element and
allows you to create an button that displays an image.

<input type=image
id="programmaticID"
src="imagepath"
align="imagealignment"
alt="alttext"
OnServerClick="onserverclickhandler"
width="borderwidthinpixels"
runat="server" >
Remarks

Use the HtmlInputImage control to program against the HTML <input type=image>
element. You can use this control in conjunction with the HtmlInputText, HtmlTextArea,
and other controls to construct user input forms. Because this control is the <input
type=image> element that is run on the server, it offers the same button customization as
HTML. This control offers an alternative for browsers that do not support DHTML and the
HtmlButton control.

Note This control does not require a closing tag.

One of the advantages of HTML controls over Web controls is that server-side events do not
conflict with events that occur on the client, unless the server and client code themselves
countermand each other. This being the case, you can use dynamic HTML (DHTML) events
to modify the appearance of any image that you include on your Web Forms page.

Example

The following example compares a static image button control with an image button control
that uses the DHTML onMouseOver event (which displays the image of a banana) and the
onMouseOut event (which displays the original mango image). Both image buttons include
an OnServerClick event handler.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Button1_Click(Source As Object, e As ImageClickEventArgs)
Span1.InnerHtml = "You clicked button1"
End Sub

Sub Button2_Click(Source As Object, e As ImageClickEventArgs)


Span1.InnerHtml = "You clicked button2"
End Sub
</script>
</head>
<body>
<h3>HtmlInputImage Sample</h3>
<form runat="server">
<input type=image
id="InputImage1"
src="/images/mango.jpg"
OnServerClick="Button1_Click"
runat="server">
<p>
<input type=image
id="InputImage2"
src="/images/mango.jpg"
onmouseover="this.src='/images/banana.jpg';"
onmouseout="this.src='/images/mango.jpg';"
OnServerClick="Button2_Click"
runat="server">
&nbsp;With rollover effect (HTML 4.0)
<p>
<span id=Span1 runat="server" />
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Button1_Click(object Source, ImageClickEventArgs e)
{
Span1.InnerHtml="You clicked button1";
}
void Button2_Click(object Source, ImageClickEventArgs e)
{
Span1.InnerHtml="You clicked button2";
}
</script>
</head>
<body>
<h3>HtmlInputImage Sample</h3>
<form runat="server">
<input type=image
id="InputImage1"
src="/images/mango.jpg"
OnServerClick="Button1_Click"
runat="server">
<p>
<input type=image
id="InputImage2"
src="/images/mango.jpg"
onmouseover="this.src='/images/banana.jpg';"
onmouseout="this.src='/images/mango.jpg';"
OnServerClick="Button2_Click"
runat="server">
&nbsp;With rollover effect (HTML 4.0)
<p>
<span id=Span1 runat="server" />
</form>
</body>
</html>

HtmlInputRadioButton Control
Creates a server-side control that maps to the <input type=radio> HTML element and allows
you to create a radio button on a Web page.

<input type=radio
id="programmaticID"
checked
name="radiobuttongroup"
runat="server" >
Remarks

Use the HtmlInputRadioButton control to program against the HTML <input type=radio>
element. You can group multiple HtmlInputRadioButton controls together by setting the
Name property to a value that is common to all <input type=radio> elements within the
group. Radio buttons in the same group are mutually exclusive; only one radio button in the
group can be selected at a time.

Note This control does not require a closing tag.

The HtmlRadioButton control does not automatically post back to the server. You must rely
on using one of the button controls, such as the HtmlInputButton, HtmlInputImage, or
HtmlButton, to post back to the server. You can program against the HtmlRadioButton
control by writing a handler for the ServerChange event.

Note The ServerChange event is only raised for radio buttons that change to a checked state.

Example

The following example demonstrates how to create an event handler for the ServerChange
event of the HtmlRadioButton control. The event handler determines which radio button is
selected and displays the selection in a message.
VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Server_Change(Source As Object, e As EventArgs)
If Radio1.Checked = True Then
Span1.InnerHtml = "Radio1 is checked"
Else
If Radio2.Checked = True Then
Span1.InnerHtml = "Radio2 is checked"
Else
If Radio3.Checked = True Then
Span1.InnerHtml = "Radio3 is checked"
End If
End If
End If
End Sub
</script>
</head>
<body>
<form runat="server">
<h3>HtmlInputRadioButton Sample</h3>
<input type="radio"
id="Radio1"
name="Mode"
OnServerChange="Server_Change"
runat="server"/>
Option 1<br>
<input type="radio"
id="Radio2"
name="Mode"
OnServerChange="Server_Change"
runat="server"/>
Option 2<br>
<input type="radio"
id="Radio3"
name="Mode"
OnServerChange="Server_Change"
runat="server"/>
Option 3
<p>
<span id=Span1 runat="server" />
<p>
<input type=submit id="Button1"
value="Enter"
runat="server">
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Server_Change(object Source, EventArgs e)
{
if (Radio1.Checked == true)
Span1.InnerHtml = "Radio1 is checked";
else if (Radio2.Checked == true)
Span1.InnerHtml = "Radio2 is checked";
else if (Radio3.Checked == true)
Span1.InnerHtml = "Radio3 is checked";
}
</script>
</head>
<body>
<form runat="server">
<h3>HtmlInputRadioButton Sample</h3>
<input type="radio"
id="Radio1"
name="Mode"
OnServerChange="Server_Change"
runat="server"/>
Option 1<br>
<input type="radio"
id="Radio2"
name="Mode"
OnServerChange="Server_Change"
runat="server"/>
Option 2<br>
<input type="radio"
id="Radio3"
name="Mode"
OnServerChange="Server_Change"
runat="server"/>
Option 3
<p>
<span id=Span1 runat="server" />
<p>
<input type=submit id="Button1"
value="Enter"
runat="server">
</form>
</body>
</html>

HtmlInputText Control
Creates a server-side control that maps to the <input type=text> and <input
type=password> HTML elements and allows you to create a single line text box to receive
user input.

<input type=text | password


id="programmaticID"
maxlength="max#ofcharacters"
size="widthoftextbox"
value="defaulttextboxcontents"
runat="server" >
Remarks

Use the HtmlInputText control to run server code against the <input type=text> and
<input type=password> HTML elements. As with standard HTML, these controls can be
used to enter user names and passwords in HTML forms.

Note When the Type property is set to password, your entry is masked in the text box.

You can use this control in conjunction with the HtmlInputButton, HtmlInputImage, or
HtmlButton control to process user input on the server. You can control the number of
characters that can be entered, the width, and the contents of the control by using the
MaxLength, Size, and Value properties, respectively.

Note This control does not require a closing tag.


Example

The following example demonstrates how use the HtmlInputText control to get user input.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>

<html>

<head>

<script runat="server">

Protected Sub AddButton_Click(sender As Object, e As EventArgs)

Dim Answer As Integer

Answer = Convert.ToInt32(Value1.Value) +
Convert.ToInt32(Value2.Value)

AnswerMessage.InnerHtml = Answer.ToString()

End Sub

</script>

</head>

<body>

<form runat="server">

<h3> HtmlInputText Example </h3>

<table>

<tr>
<td colspan="5">

Enter integer values into the text boxes. <br>


Click the Add button to add the two values. <br>
Click the Reset button to reset the text boxes.

</td>

</tr>

<tr>

<td colspan="5">

&nbsp;

</td>

</tr>

<tr align="center">

<td>

<input ID="Value1"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>

</td>

<td>

</td>

<td>

<input ID="Value2"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>

</td>

<td>

</td>
<td>

<span ID="AnswerMessage"
runat="server"/>

</td>

</tr>

<tr>

<td colspan="2">

<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="Value1"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value1MinCompareValidator"
ControlToValidate="Value1"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value1MaxCompareValidator"
ControlToValidate="Value1"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>

<td colspan="2">

<asp:RequiredFieldValidator
ID="Value2RequiredValidator"
ControlToValidate="Value2"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MinCompareValidator"
ControlToValidate="Value2"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MaxCompareValidator"
ControlToValidate="Value2"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>

<td>

&nbsp

</td

</tr>

<tr align="center">

<td colspan="4">

<input Type="Submit"
Name="AddButton
Value="Add"
OnServerClick="AddButton_Click"
runat="server"/>

&nbsp;&nbsp;&nbsp;

<input Type="Reset"
Name="AddButton
Value="Reset"
runat="server"/>

</td>

<td>

&nbsp;

</td>

</tr>

</table>
</form>

</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>

<html>

<head>

<script runat="server">

protected void AddButton_Click(Object sender, EventArgs e)


{
int Answer;

Answer = Convert.ToInt32(Value1.Value) +
Convert.ToInt32(Value2.Value);

AnswerMessage.InnerHtml = Answer.ToString();

</script>

</head>

<body>

<form runat="server">

<h3> HtmlInputButton Example </h3>

<table>

<tr>

<td colspan="5">

Enter integer values into the text boxes. <br>


Click the Add button to add the two values. <br>
Click the Reset button to reset the text boxes.

</td>

</tr>

<tr>

<td colspan="5">

&nbsp;

</td>

</tr>
<tr align="center">

<td>

<input ID="Value1"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>

</td>

<td>

</td>

<td>

<input ID="Value2"
Type="Text"
Size="2"
MaxLength="3"
Value="1"
runat="server"/>

</td>

<td>

</td>

<td>

<span ID="AnswerMessage"
runat="server"/>

</td>

</tr>

<tr>

<td colspan="2">

<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="Value1"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>
<asp:CompareValidator
ID="Value1MinCompareValidator"
ControlToValidate="Value1"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value1MaxCompareValidator"
ControlToValidate="Value1"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>

<td colspan="2">

<asp:RequiredFieldValidator
ID="Value2RequiredValidator"
ControlToValidate="Value2"
ErrorMessage="Please enter an value.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MinCompareValidator"
ControlToValidate="Value2"
Operator="LessThan"
Type="Integer"
ValueToCompare="100"
ErrorMessage="Please enter an integer less than
100.<br>"
Display="Dynamic"
runat="server"/>

<asp:CompareValidator
ID="Value2MaxCompareValidator"
ControlToValidate="Value2"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="0"
ErrorMessage="Please enter an integer greater than
0.<br>"
Display="Dynamic"
runat="server"/>

</td>
<td>

&nbsp

</td

</tr>

<tr align="center">

<td colspan="4">

<input Type="Submit"
Name="AddButton
Value="Add"
OnServerClick="AddButton_Click"
runat="server"/>

&nbsp;&nbsp;&nbsp;

<input Type="Reset"
Name="AddButton
Value="Reset"
runat="server"/>

</td>

<td>

&nbsp;

</td>

</tr>

</table>

</form>

</body>
</html>

HtmlSelect Control
Creates a server-side control that maps to the <select> HTML element and allows you to
create a list control.

<select id="programmaticID"
OnServerChange="onserverchangehandler"
DataSource="databindingsource"
DataMember="datamembervalue"
DataTextField="fieldtodatabindoptionttext"
DataValueField="fieldtodatabindoptionvalue"
Multiple
Items="collectionofoptionelements"
SelectedIndex="indexofcurrentlyselecteditem"
Size="#ofvisibleitems"
Value="currentitemvalue"
runat="server" >

<option>value1</option>
<option>value2</option>

</select>
Remarks

Use the HtmlSelect control to program against the HTML <select> element. By default, this
control renders as a drop-down list box. However, if you allow multiple selections (by
specifying the Multiple attribute) or specify a value for the Size property that is greater than
1, the control is displayed as a list box.

To determine the selected item from a single selection HtmlSelect control, first use the
SelectedItem property to obtain the index of the selected item. You can then use this index to
retrieve the selected item from the Items collection.

To determine the selected items from an HtmlSelect control that allows multiple selections
simultaneously, you need to iterate through the Items collection and test the Selected
property of each item.

You can also bind the control to a data source. Set the DataSource property to specify the
data source to bind to the control. Once the data source is bound to the control, you can
specify which field to bind to the Value and Text properties by setting the DataValueField
and DataTextField properties, respectively.

Example

The following example uses entries in an HtmlSelect control to set the background color for a
span control. It also shows how to use the Items property to add new option items to the
select list. This property is of the ListItemCollection type and can therefore access that class's
Add method. The example code does this in the AddToList_Click event handler.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Apply_Click(Source As Object, e As EventArgs)
Span1.Style("background-color") = ColorSelect.Value
End Sub

Sub AddToList_Click(Source As Object, e As EventArgs)


ColorSelect.Items.Add(Text1.Value)
End Sub
</script>
</head>
<body>
<h3>HtmlSelect Sample</h3>
<form runat="server">
Select a color:<br>
<select id="ColorSelect" runat="server">
<option>SkyBlue</option>
<option>LightGreen</option>
<option>Gainsboro</option>
<option>LemonChiffon</option>
</select>
<input type="button" runat="server"
Value="Apply" OnServerClick="Apply_Click">
<p>
Don't see your color in the list above? You can add it here:<br>
<input type="text" id="Text1" runat="server">
<input type="button" runat="server"
Value="Add to List" OnServerClick="AddToList_Click">
<p>
<span id="Span1" runat="server">
Click the button to apply a background color to this span.
</span>
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Apply_Click(object Source, EventArgs e)
{
Span1.Style["background-color"] = ColorSelect.Value;
}
void AddToList_Click(object Source, EventArgs e)
{
ColorSelect.Items.Add(Text1.Value);
}
</script>
</head>
<body>
<h3>HtmlSelect Sample</h3>
<form runat="server">
Select a color:<br>
<select id="ColorSelect" runat="server">
<option>SkyBlue</option>
<option>LightGreen</option>
<option>Gainsboro</option>
<option>LemonChiffon</option>
</select>
<input type="button" runat="server"
Value="Apply" OnServerClick="Apply_Click">
<p>
Don't see your color in the list above? You can add it here:<br>
<input type="text" id="Text1" runat="server">
<input type="button" runat="server"
Value="Add to List" OnServerClick="AddToList_Click">
<p>
<span id="Span1" runat="server">
Click the button to apply a background color to this span.
</span>
</form>
</body>
</html>

The following example shows how to bind an HtmlSelect control to an ArrayList that is
declared in the Page_Load event. There is also a SubmitBtn_Click event that displays the
selected data bound value when the user clicks an HtmlInputButton control on the rendered
page.

The Id property for the select control is StateSelect and the control's DataSource property is
set to the values that ArrayList creates when the page is loaded. Then the select control's
DataBind method binds the values in the ArrayList to the control itself.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Page_Load(Sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim values As New ArrayList()
values.Add("IN")
values.Add("KS")
values.Add("MD")
values.Add("MI")
values.Add("OR")
values.Add("TN")
StateSelect.DataSource = values
StateSelect.DataBind()
End If
End Sub

Sub SubmitBtn_Click(sender As Object, e As EventArgs)


Span1.InnerHtml = "You chose: " & StateSelect.Value
End Sub
</script>
</head>
<body>
<h3>Data Binding to an HtmlSelect Control</h3>
<form runat="server">
Select a state:<br>
<select id="StateSelect" runat="server" />
<input type="submit" value="Display Selected State"
OnServerClick="SubmitBtn_Click" runat="server">
<p>
<span id="Span1" runat="server" />
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Page_Load(Object Sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList values = new ArrayList();
values.Add ("IN");
values.Add ("KS");
values.Add ("MD");
values.Add ("MI");
values.Add ("OR");
values.Add ("TN");
StateSelect.DataSource = values;
StateSelect.DataBind();
}
}
void SubmitBtn_Click(Object sender, EventArgs e)
{
Span1.InnerHtml = "You chose: " + StateSelect.Value;
}
</script>
</head>
<body>
<h3>Data Binding to an HtmlSelect Control</h3>
<form runat="server">
Select a state:<br>
<select id="StateSelect" runat="server" />
<input type="submit" value="Display Selected State"
OnServerClick="SubmitBtn_Click" runat="server">
<p>
<span id="Span1" runat="server" />
</form>
</body>
</html>

HtmlTable Control
Creates a server-side control that maps to the <table> HTML element and allows you to
create a table.

<table id="programmaticID"
align=left | center | right
bgcolor="bgcolor"
border="borderwidthinpixels"
bordercolor="bordercolor"
cellpadding="spacingwithincellsinpixels"
cellspacing="spacingbetweencellsinpixels"
height="tableheight"
rows="collectionofrows"
width="tablewidth"
runat="server" >

<tr>
<td></td>
</tr>
</table>
Remarks

Use the HtmlTable control to program against the HTML <table> element. An HtmlTable
control is made up of rows (represented by HtmlTableRow objects) stored in the Rows
collection of a table. Each row is made up of cells (represented by HtmlTableCell objects)
stored in the Cells collection of a row.

To create a table, first declare an HtmlTable control in the form on your page. Next, place
HtmlTableRow objects between the opening and closing tags of the HtmlTable control, one
for each row you want in your table. Once the rows of the table are defined, declare
HtmlTableCell objects between the opening and closing tags of each HtmlTableRow object
to create the cells of the row.

Note Make sure you have correct number of cells in each row and column, otherwise the table
might not display as expected. In general, each row should have the same number or cells. Likewise,
each column should also share the same number of cells. If you're spanning cells, each row should be
the same width and each column should be the same height.

The HtmlTable control allows you to customize the appearance of a table. You can specify
the background color, border width, border color, table height, and table width of the table by
setting the BgColor, Border, BorderColor, Height, and Width properties, respectively. You
can also control spacing between cells and spacing between the contents of a cell and the cell
border by setting the CellSpacing and CellPadding properties.

Example

The following example generates table rows and table cells, based on user selections from two
HtmlSelect controls. Every time the page is loaded, the code checks to see what values the
user has selected in the HtmlSelect controls. The number of rows and columns in the
HtmlTable control is dynamically generated based on these values. To construct a table,
create the rows of the table (represented by HtmlTableRow objects) and add them to the
Rows collection of the HtmlTable control. To construct the rows, create the cells of the row
(represented by HtmlTableCell objects) and add them to Cells collection of the
HtmlTableRow.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim row As Integer = 0
' Generate rows and cells.
Dim numrows As Integer = Convert.ToInt32(Select1.Value)
Dim numcells As Integer = Convert.ToInt32(Select2.Value)
Dim j As Integer
For j = 0 To numrows - 1
Dim r As New HtmlTableRow()
' Set bgcolor on alternating rows.
If row Mod 2 = 1 Then
r.BgColor = "Gainsboro"
End If
row += 1
Dim i As Integer
For i = 0 To numcells - 1
Dim c As New HtmlTableCell()
c.Controls.Add(New LiteralControl("row " & j.ToString() & _
", cell " & i.ToString()))
r.Cells.Add(c)
Next i
Table1.Rows.Add(r)
Next j
End Sub
</script>
</head>
<body>
<h3>HtmlTable Example</h3>
<form runat="server">
<p>
<table id="Table1"
CellPadding=5
CellSpacing=0
Border="1"
BorderColor="black"
runat="server" />
<p>
Table rows:
<select id="Select1" runat="server">
<option Value="1">1</option>
<option Value="2">2</option>
<option Value="3">3</option>
<option Value="4">4</option>
<option Value="5">5</option>
</select>
<br>
Table cells:
<select id="Select2" runat="server">
<option Value="1">1</option>
<option Value="2">2</option>
<option Value="3">3</option>
<option Value="4">4</option>
<option Value="5">5</option>
</select>
<input type="submit" value="Generate Table" runat="server">
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
int row = 0;
// Generate rows and cells.
int numrows = Convert.ToInt32(Select1.Value);
int numcells = Convert.ToInt32(Select2.Value);
for (int j=0; j<numrows; j++)
{
HtmlTableRow r = new HtmlTableRow();
// Set bgcolor on alternating rows.
if (row%2 == 1)
r.BgColor="Gainsboro";
row++;
for (int i=0; i<numcells; i++)
{
HtmlTableCell c = new HtmlTableCell();
c.Controls.Add(new LiteralControl("row " + j.ToString() +
", cell " + i.ToString()));
r.Cells.Add(c);
}
Table1.Rows.Add(r);
}
}
</script>
</head>
<body>
<h3>HtmlTable Example</h3>
<form runat="server">
<p>
<table id="Table1"
CellPadding=5
CellSpacing=0
Border="1"
BorderColor="black"
runat="server" />
<p>
Table rows:
<select id="Select1" runat="server">
<option Value="1">1</option>
<option Value="2">2</option>
<option Value="3">3</option>
<option Value="4">4</option>
<option Value="5">5</option>
</select>
<br>
Table cells:
<select id="Select2" runat="server">
<option Value="1">1</option>
<option Value="2">2</option>
<option Value="3">3</option>
<option Value="4">4</option>
<option Value="5">5</option>
</select>
<input type="submit" value="Generate Table" runat="server">
</form>
</body>
</html>

HtmlTableCell Control
Creates a server-side control that maps to the <td> and <th> HTML elements and allows you
manipulate a cell in a table.

<td or th id="programmaticID"
align="alignmentofcontentincell"
bgcolor="bgcolor"
bordercolor="bordercolor"
colspan="#ofcolscellspans"
height="cellheight"
nowrap="True | False"
rowspan="#ofrowscellspans"
valign="vertalignmentofcellcontent"
width="cellwidth">
CellContent
</td or /th>
Remarks

Use the HtmlTableCell class to program against the <td> and <th> HTML elements. A <td>
element represents a data cell, while the <th> element represents a heading cell. Note that the
contents of a <th> cell are always bold and centered.

The HtmlTableCell class allows you to control the appearance of each indivual cell. You can
control the background color, border color, height, and width of the cell by setting the
BgColor, BorderColor, Height, and Width properties respectively.

Note All cells in the same row share the same height. The tallest cell in a row determines the height
of all cells in the row.

The horizontal and vertical alignment of the contents of the cell are controlled by setting the
Align and VAlign properties, respectively. You can also specify whether the text
automatically continues on the next line of the cell by setting the NoWrap property.

The HtmlTableCell class allows you to span cells by setting the ColSpan and RowSpan
properties. The ColSpan property lets you control how many columns a cell occupies, while
the rowspan property specifies the number of rows a cell occupies.

Note When spanning cells, be sure that each row in the table is the same length. Also make sure
that each column is the same height. Otherwise, the table might not display as expected.
Example

The following example demonstrates how use an HtmlTableCell object to modify the
contents of a cell in the HtmlTable control.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>

<html>
<head>
<script runat="server">
Sub Button_Click(sender As Object, e As EventArgs)

Dim i As Integer
Dim j As Integer
' Iterate through the rows of the table.
For i=0 To Table1.Rows.Count - 1
' Iterate through the cells of a row.
For j=0 To Table1.Rows(i).Cells.Count - 1
' Change the inner HTML of the cell.
Table1.Rows(i).Cells(j).InnerHtml = "Row " & i.ToString() _
& ", Column " & _
j.ToString()
Next j
Next i
End Sub
</script>

</head>
<body>
<form runat="server">
<h3>HtmlTableCell Example</h3>
<table id="Table1"
Border="1"
BorderColor="black"
runat="server">

<tr>
<td>
Cell 1
</td>
<td>
Cell 2
</td>
</tr>
<tr>
<td>
Cell 3
</td>
<td>
Cell 4
</td>
</tr>
</table>
<br><br>
<input type="button"
value="Change Table Contents"
OnServerClick = "Button_Click"
runat="server"/>

</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>

<html>
<head>
<script runat="server">
void Button_Click(Object sender, EventArgs e)
{
// Iterate through the rows of the table.
for (int i=0; i<=Table1.Rows.Count - 1; i++)
{
// Iterate through the cells of a row.
for (int j=0; j<=Table1.Rows[i].Cells.Count - 1; j++)
{
// Change the inner HTML of the cell.
Table1.Rows[i].Cells[j].InnerHtml = "Row " + i.ToString() +
", Column " +
j.ToString();
}
}
}
</script>
</head>
<body>

<form runat="server">

<h3>HtmlTableCell Example</h3>

<table id="Table1"
Border="1"
BorderColor="black"
runat="server">

<tr>
<td>
Cell 1
</td>
<td>
Cell 2
</td>
</tr>
<tr>
<td>
Cell 3
</td>
<td>
Cell 4
</td>
</tr>

</table>
<br><br>
<input type="button"
value="Change Table Contents"
OnServerClick = "Button_Click"
runat="server"/>
</form>
</body>
</html>

HtmlTableRow Control

Creates a server-side control that maps to the <tr> HTML element and allows you to create
and manipulate a row in a table.

<tr id="programmaticID"
align="tablecontentalignment"
bgcolor="tablebgcolor"
bordercolor="bordercolor"
height="tableheight"
cells="collectionoftablecells"
valign="verticalalignmentofrowcontent" >

<td>cellcontent</td>
<td>cellcontent</td>
<td>cellcontent</td>

</tr>
Remarks

Use the HtmlTableRow class to program against the <tr> HTML element. A <tr> element
represents a row in the table.

The HtmlTableRow class allows you to control the appearance of each individual row in the
table. You can control the background color, border color, and height of the row by setting the
BgColor, BorderColor, and Height properties, respectively.

The horizontal and vertical alignment of the contents of the cells in the row are controlled by
setting the Align and VAlign properties, respectively.

Each row in the table contains a Cells collection, which contains an HtmlTableCell for each
cell in the row.
Example

The following example demonstrates how use an HtmlTableCell to modify the contents of a
cell in the HtmlTable control.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>

<html>
<head>

<script runat="server">

Sub Button_Click(sender As Object, e As EventArgs)

Dim i As Integer
Dim j As Integer

' Iterate through the rows of the table.


For i=0 To Table1.Rows.Count - 1

' Iterate through the cells of a row.


For j=0 To Table1.Rows(i).Cells.Count - 1

' Change the inner HTML of the cell.


Table1.Rows(i).Cells(j).InnerHtml = "Row " & i.ToString() _
& ", Column " & _
j.ToString()
Next j

Next i

End Sub

</script>

</head>
<body>

<form runat="server">

<h3>HtmlTableCell Example</h3>

<table id="Table1"
Border="1"
BorderColor="black"
runat="server">

<tr>
<td>
Cell 1
</td>
<td>
Cell 2
</td>
</tr>
<tr>
<td>
Cell 3
</td>
<td>
Cell 4
</td>
</tr>

</table>

<br><br>

<input type="button"
value="Change Table Contents"
OnServerClick = "Button_Click"
runat="server"/>

</form>

</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>

<html>
<head>

<script runat="server">

void Button_Click(Object sender, EventArgs e)


{

// Iterate through the rows of the table.


for (int i=0; i<=Table1.Rows.Count - 1; i++)
{

// Iterate through the cells of a row.


for (int j=0; j<=Table1.Rows[i].Cells.Count - 1; j++)
{
// Change the inner HTML of the cell.
Table1.Rows[i].Cells[j].InnerHtml = "Row " + i.ToString() +
", Column " +
j.ToString();
}

</script>

</head>
<body>

<form runat="server">
<h3>HtmlTableCell Example</h3>

<table id="Table1"
Border="1"
BorderColor="black"
runat="server">

<tr>
<td>
Cell 1
</td>
<td>
Cell 2
</td>
</tr>
<tr>
<td>
Cell 3
</td>
<td>
Cell 4
</td>
</tr>

</table>

<br><br>

<input type="button"
value="Change Table Contents"
OnServerClick = "Button_Click"
runat="server"/>

</form>

</body>
</html>

HtmlTextArea Control
Creates a server-side control that maps to the <textarea> HTML element and allows you
create a multiline text box.

<textarea id="programmaticID"
cols="numberofcolsintextarea"
name="namepassedtobrowser"
rows="numberofrowsintextarea"
onserverchange="onserverchangehandler"
runat="server" >
textareacontent
</textarea>
Remarks

Use the HtmlTextArea control to program against the HTML <textarea> element. This
control allows you to create a multiline text box. The dimensions of the text box are
controlled by the Cols and Rows properties. The Cols property determines the width of the
control, while the Rows property determines the height of the control.

The HtmlTextArea control contains a ServerChange event that is raised when the contents
of the control change between posts to the server. The event is commonly used to validate the
text entered in the control.

Example

The following example demonstrates how to use the OnServerClick event handler of an
HtmlInputButton control to display user input from an HtmlTextArea control. The text is
displayed by a span control in the Web Forms page. You can use similar techniques to store
the text area's values on the server.

VB
<%@ Page Language="VB" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
Sub SubmitBtn_Click(sender As Object, e As EventArgs)
Span1.InnerHtml = "You wrote: <br>" & TextArea1.Value
End Sub
</script>
</head>
<body>
<h3>HtmlTextArea Example</h3>
<form runat=server>
What do you like best about ASP.NET?: <br>
<textarea id="TextArea1" cols=40 rows=4 runat=server />
<input type=submit value="Submit"
OnServerClick="SubmitBtn_Click" runat=server>
<p>
<span id="Span1" runat="server" />
</form>
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void SubmitBtn_Click(Object sender, EventArgs e)
{
Span1.InnerHtml = "You wrote: <br>" + TextArea1.Value;
}
</script>
</head>
<body>
<h3>HtmlTextArea Example</h3>
<form runat=server>
What do you like best about ASP.NET?: <br>
<textarea id="TextArea1" cols=40 rows=4 runat=server />
<input type=submit value="Submit"
OnServerClick="SubmitBtn_Click" runat=server>
<p>
<span id="Span1" runat="server" />
</form>
</body>
</html>

System.Web.UI.HtmlControls Namespace
The System.Web.UI.HtmlControls namespace is a collection of classes that allow you to
create HTML server controls on a Web Forms page. HTML server controls run on the server
and map directly to standard HTML tags supported by most browsers. This allows you to
programmatically control the HTML elements on a Web Forms page.

Namespace hierarchy

Classes
Class Description

HtmlAnchor Allows programmatic access to the HTML <a> tag


on the server.

HtmlButton Allows programmatic access to the HTML


<button> tag on the server.

HtmlContainerControl Defines the methods, properties, and events


available to all HTML server controls that must
have a closing tag.

HtmlControl Defines the methods, properties, and events


common to all HTML server controls in the Web
Forms page framework.

HtmlForm Provides programmatic access to the HTML


<form> element on the server.

HtmlGenericControl Defines the methods, properties, and events for


all HTML server control tags not represented by a
specific .NET Framework class.
HtmlImage Provides programmatic access for the HTML
<img> element on the server.

HtmlInputButton Allows programmatic access to the HTML <input


type= button>, <input type= submit>, and <input
type= reset> elements on the server.

HtmlInputCheckBox Allows programmatic access to the HTML <input


type= checkbox> element on the server.

HtmlInputControl Serves as the abstract base class that defines the


methods, properties, and events common to all
HTML input controls, such as the <input
type=text>, <input type=submit>, and <input
type= file> elements.

HtmlInputFile Allows programmatic access to the HTML <input


type= file> element on the server.

HtmlInputHidden Allows programmatic access to the HTML <input


type=hidden> element on the server.

HtmlInputImage Allows programmatic access to the HTML <input


type= image> element on the server.

HtmlInputRadioButton Allows programmatic access to the HTML <input


type= radio> element on the server.

HtmlInputText Allows programmatic access to the HTML <input


type= text> and <input type= password>
elements on the server.

HtmlSelect Allows programmatic access to the HTML


<select> element on the server.

HtmlTable Allows programmatic access on the server to the


HTML <table> element.

HtmlTableCell Represents the <td> and <th> HTML elements in


an HtmlTableRow.

HtmlTableCellCollection A collection of HtmlTableCell objects that


represent the cells in a single row of an
HtmlTable control. This class cannot be inherited.

HtmlTableRow Represents the <tr> HTML element in an


HtmlTable control.
HtmlTableRowCollection A collection of HtmlTableRow objects that
represent the rows of an HtmlTable control. This
class cannot be inherited.

HtmlTextArea Allows programmatic access to the <textarea>


HTML element on the server.

You might also like