asp w3schools

Upload: vijay-vishwakarma

Post on 10-Apr-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 ASP W3schools

    1/100

    ASP.NET Introduction

    ASP.NET is the latest version of Microsoft's Active Server Pages technology (ASP).

    What you should already know

    Before you continue you should have a basic understanding of the following:

    WWW, HTML and the basics of building Web pages

    Scripting languages like JavaScript or VBScript

    The basics of server side scripting

    What is ASP?

    ASP is a server side scripting technology that enables scripts (embedded in web pages) to beexecuted by an Internet server.

    ASP is a Microsoft Technology

    ASP stands for Active Server Pages

    ASP is a program that runs inside IIS

    IIS stands for Internet Information Services

    IIS comes as a free component with Windows 2000

    IIS is also a part of the Windows NT 4.0 Option Pack

    The Option Pack can be downloaded from Microsoft

    PWS is a smaller - but fully functional - version of IIS

    PWS can be found on your Windows 95/98 CD

    What is an ASP File?

    An ASP file is just the same as an HTML file

    An ASP file can contain text, HTML, XML, and scripts

    Scripts in an ASP file are executed on the server

    An ASP file has the file extension ".asp"

    How Does it Work?

    When a browser requests an HTML file, the server returns the file

    When a browser requests an ASP file, IIS passes the request to the ASP engine on theserver

    The ASP engine reads the file, line by line, and executes the scripts in the file

    Finally, the ASP file is returned to the browser as plain HTML

    Before you study ASP .NET, it would help to have a basic understanding of Microsoft's ASPtechnology.

    What is ASP+?

  • 8/8/2019 ASP W3schools

    2/100

    ASP+ is the same as ASP.NET.

    ASP+ is just an early name used by Microsoft when they developed ASP.NET.

    What is ASP.NET?

    ASP 3.0 is the latest version of ASP, but there will never be an ASP 4.0 version.

    ASP.NET is the next generation ASP, but it's not an upgraded version of ASP. ASP.NET is an entirelynew paradigm for server-side ASP scripting.

    ASP.NET is a part of the .NET Framework. Microsoft spent three years rewriting ASP.NET from theground up, and ASP.NET is not fully backward compatible with ASP 3.0.

    .NET Framework

    The .NET Framework is the infrastructure for the Microsoft .NET platform.

    The .NET Framework is an environment for building, deploying, and running Web applications and

    Web Services.

    The .NET Framework contains a common language runtime and common class libraries - likeADO.NET, ASP.NET and Windows Forms - to provide advanced standard services that can beintegrated into a variety of computer systems.

    The .NET Framework provides a feature-rich application environment, simplified development andeasy integration between a number of different development languages.

    The .NET Framework is language neutral. Currently it supports C++, C#, Visual Basic, and JScript(Microsoft's version of JavaScript).

    Microsoft's Visual Studio.NET is a common development environment for the .NET Framework.

    Differences between ASP and ASP .NET

    ASP .NET has better language support, a large set of new controls and XML basedcomponents, and better user authentication.

    ASP .NET provides increased performance by running compiled code.

    ASP .NET code is not fully backward compatible with ASP.New in ASP .NET

    Better language support

    Programmable controls

    Event-driven programming

    XML-based components

    User authentication, with accounts and roles

    Higher scalability

    Increased performance - Compiled code

    Easier configuration and deployment

    Not fully ASP compatible

    Language Support

    ASP .NET uses the new ADO .NET.

  • 8/8/2019 ASP W3schools

    3/100

    ASP .NET supports full Visual Basic, not VBScript.

    ASP .NET supports C# (C sharp) and C++.

    ASP .NET supports JScript as before.

    ASP .NET Controls

    ASP .NET contains a large set of HTML controls. Almost all HTML elements on a page can be definedas ASP .NET control objects that can be controlled by scripts.

    ASP .NET also contains a new set of object oriented input controls, like programmable list boxes andvalidation controls.

    A new data grid control supports sorting, data paging, and everything you expect from a datasetcontrol.

    Event Aware Controls

    All ASP .NET objects on a Web page can expose events that can be processed by ASP .NET code.

    Load, Click and Change events handled by code makes coding much simpler and much betterorganized.

    ASP .NET Components

    ASP .NET components are heavily based on XML. Like the new AD Rotator, that uses XML to storeadvertisement information and configuration.

    User Authentication

    ASP .NET supports forms-based user authentication, including cookie management and automaticredirecting of unauthorized logins.

    (You can still do your custom login page and custom user checking).

    User Accounts and Roles

    ASP .NET allows for user accounts and roles, to give each user (with a given role) access to differentserver code and executables.

    High Scalability

    Much has been done with ASP .NET to provide greater scalability.

    Server to server communication has been greatly enhanced, making it possible to scale anapplication over several servers. One example of this is the ability to run XML parsers, XSLtransformations and even resource hungry session objects on other servers.

  • 8/8/2019 ASP W3schools

    4/100

    Compiled Code

    The first request for an ASP .NET page on the server will compile the ASP .NET code and keep acached copy in memory. The result of this is greatly increased performance.

    Easy Configuration

    Configuration of ASP .NET is done with plain text files.

    Configuration files can be uploaded or changed while the application is running. No need to restartthe server. No more metabase or registry puzzle.

    Easy Deployment

    No more server restart to deploy or replace compiled code. ASP .NET simply redirects all newrequests to the new code.

    Compatibility

    ASP .NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will needsome changes to run under ASP .NET.

    To overcome this problem, ASP .NET uses a new file extension ".aspx". This will make ASP .NETapplications able to run side by side with standard ASP applications on the same server.

    Installing ASP.NET

    ASP.NET is easy to install. Just follow the instructions below.

    What You Need

  • 8/8/2019 ASP W3schools

    5/100

    A Windows Computer

    ASP.NET is a Microsoft technology. To run ASP.NET you need a computer capable of runningWindows.

    Windows 2000 or XP

    If you are serious about developing ASP.NET applications you should install Windows 2000

    Professional or Windows XP Professional.

    In both cases, make sure you install the Internet Information Services (IIS) from the Add/RemoveWindows components dialog.

    Service Packs and Updates

    Before ASP.NET can be installed on your computer, it is necessary to have all relevant service packsand security updates installed.

    The easiest way to do this is to activate your Windows Internet Update. When you access theWindows Update page, you will be instructed to install the latest service packs and all criticalsecurity updates. For Windows 2000, make sure you install Service Pack 2. I will also recommend

    that you install Internet Explorer 6.

    Read the note about connection speed and download time at the bottom of this page.

    Remove Your Beta Version

    If you have a Beta version of ASP.NET installed, we recommend that you completely uninstall it. Oreven better: start with a fresh Windows 2000 or XP installation.

    Install .NET

    From your Windows Update you can now select to install the Microsoft .NET Framework.

    After download, the .NET framework will install itself on your computer - there are no options toselect for installation.

    You should now be ready to develop your first ASP.NET application!

    The .NET Software Development Kit

    If you have the necessary bandwidth to download over 130 MB, you might consider downloadingthe full Microsoft .NET Software Development Kit (SDK).

    We fully recommend getting the SDK for learning more about .NET and for the documentation,samples, and tools included.

    Connection Speed and Download Time

    If you have a slow Internet connection, you might have problems downloading large files like theservice packs, the SDK and the latest version of Internet Explorer.

    If download speed is a problem, our best suggestion is to get the latest files from someone else,from a colleague, from a friend, or from one of the CDs that comes with many popular computermagazines. Look for Windows 2000 Service Pack 2, Internet Explorer 6, and the Microsoft .NET

    Framework.

  • 8/8/2019 ASP W3schools

    6/100

    ASP.NET - Web Pages

    A simple ASP.NET page looks just like an ordinary HTML page.

    Hello W3Schools

    To start learning ASP.NET, we will construct a very simple HTML page that will display "HelloW3Schools" in an Internet browser like this:

    Hello W3Schools!

    Hello W3Schools in HTML

    This code displays the example as an HTML page:

    Hello W3Schools!

    If you want to try it yourself, save the code in a file called "firstpage.htm", and create a link to thefile like this: firstpage.htm

    Hello W3Schools in ASP.NET

    The simplest way to convert an HTML page into an ASP.NET page is to copy the HTML file to a newfile with an .aspx extension.

    This code displays our example as an ASP.NET page:

    Hello W3Schools!

    If you want to try it yourself, save the code in a file called "firstpage.aspx", and create a link tothe file like this: firstpage.aspx

    How Does it Work?

    Fundamentally an ASP.NET page is just the same as an HTML page.

  • 8/8/2019 ASP W3schools

    7/100

    An HTML page has the extension .htm. If a browser requests an HTML page from the server, theserver sends the page to the browser without any modifications.

    An ASP.NET page has the extension .aspx. If a browser requests an ASP.NET page, the serverprocesses any executable code in the page, before the result is sent back to the browser.

    The ASP.NET page above does not contain any executable code, so nothing is executed. In the nextexamples we will add some executable code to the page to demonstrate the difference between

    static HTML pages and dynamic ASP pages.

    Classic ASP

    Active Server Pages (ASP) has been around for several years. With ASP, executable code can beplaced inside HTML pages.

    Previous versions of ASP (before ASP .NET) are often called Classic ASP.

    ASP .NET is not fully compatible with Classic ASP, but most Classic ASP pages will work fine asASP .NET pages, with only minor changes.

    Dynamic Page in Classic ASP

    To demonstrate how ASP can display pages with dynamic content, we have added some executablecode (in red) to the previous example:

    Hello W3Schools!

    The code inside the tags is executed on the server.

    Response.Write is ASP code for writing something to the HTML output stream.

    Now() is a function returning the servers current date and time.

    If you want to try it yourself, save the code in a file called "dynpage.asp", and create a link to thefile like this: dynpage.asp

    Dynamic Page in ASP .NET

    This following code displays our example as an ASP .NET page:

    Hello W3Schools!

    If you want to try it yourself, save the code in a file called "dynpage.aspx", and create a link to thefile like this: dynpage.aspx

  • 8/8/2019 ASP W3schools

    8/100

    ASP .NET vs Classic ASP

    The previous examples didn't demonstrate any differences between ASP .NET and Classic ASP.

    As you can see from the two latest examples there are no differences between the two ASP and ASP.NET pages.

    In the next chapters you will see how server controls make ASP. NET more powerful than Classic

    ASP.

    ASP .NET Controls

    ASP.NET - Server Controls

    Server controls are tags that are understood by the server.

    Limitations in Classic ASP

    The listing below was copied from the previous chapter:

    Hello W3Schools!

  • 8/8/2019 ASP W3schools

    9/100

    The code above illustrates a limitation in Classic ASP: The code block has to be placed where youwant the output to appear.

    With Classic ASP it is impossible to separate executable code from the HTML itself. This makes thepage difficult to read, and difficult to maintain.

    ASP.NET - Server Controls

    ASP.NET has solved the "spaghetti-code" problem described above with server controls.

    Server controls are tags that are understood by the server.

    There are three kinds of server controls:

    HTML Server Controls - Traditional HTML tags

    Web Server Controls - New ASP.NET tags

    Validation Server Controls - For input validation

    ASP.NET - HTML Server Controls

    HTML server controls are HTML tags understood by the server.

    HTML elements in ASP.NET files are, by default, treated as text. To make these elementsprogrammable, add a runat="server" attribute to the HTML element. This attribute indicates thatthe element should be treated as a server control. The id attribute is added to identify the servercontrol. The id reference can be used to manipulate the server control at run time.

    Note: All HTML server controls must be within a tag with the runat="server" attribute. Therunat="server" attribute indicates that the form should be processed on the server. It also indicatesthat the enclosed controls can be accessed by server scripts.

    In the following example we declare an HtmlAnchor server control in an .aspx file. Then we

    manipulate the HRef attribute of the HtmlAnchor control in an event handler (an event handler is asubroutine that executes code for a given event). The Page_Load event is one of many events thatASP.NET understands:

    Sub Page_Loadlink1.HRef="http://www.w3schools.com"End SubVisit W3Schools!

    The executable code itself has been moved outside the HTML.

    ASP.NET - Web Server Controls

    Web server controls are special ASP.NET tags understood by the server.

    Like HTML server controls, Web server controls are also created on the server and they require arunat="server" attribute to work. However, Web server controls do not necessarily map to anyexisting HTML elements and they may represent more complex elements.

  • 8/8/2019 ASP W3schools

    10/100

    The syntax for creating a Web server control is:

    In the following example we declare a Button server control in an .aspx file. Then we create anevent handler for the Click event which changes the text on the button:

    Sub submit(Source As Object, e As EventArgs)button1.Text="You clicked me!"End Sub

    ASP.NET - Validation Server Controls

    Validation server controls is used to validate user-input. If the user-input does not pass validation, itwill display an error message to the user.

    Each validation control performs a specific type of validation (like validating against a specific valueor a range of values).

    By default, page validation is performed when a Button, ImageButton, or LinkButton control isclicked. You can prevent validation when a button control is clicked by setting the CausesValidationproperty to false.

    The syntax for creating a Validation server control is:

    In the following example we declare one TextBox control, one Button control, and oneRangeValidator control in an .aspx file. If validation fails, the text "The value must be from 1 to100!" will be displayed in the RangeValidator control:

    Enter a number from 1 to 100:




  • 8/8/2019 ASP W3schools

    11/100

    ASP.NET - Events

    An Event Handler is a subroutine that executes code for a given event.

    ASP.NET - Event Handlers

    Look at the following code:

    When will the code above be executed? The answer is: "You don't know..."

    The Page_Load Event

    The Page_Load event is one of many events that ASP.NET understands. The Page_Load event istriggered when a page loads, and ASP.NET will automatically call the subroutine Page_Load, andexecute the code inside it:

    Sub Page_Loadlbl1.Text="The date and time is " & now()End Sub

    Note: The Page_Load event contains no object references or event arguments!

    Example:

  • 8/8/2019 ASP W3schools

    12/100

    ASPX Source:

    Sub Page_Loadlbl1.Text="The date and time is " & now()

    End Sub

    Output Result:

    The date and time is 3/10/2007 1:42:30 AM

    The Page.IsPostBack Property

    The Page_Load subroutine runs EVERY time the page is loaded. If you want to execute the code inthe Page_Load subroutine only the FIRST time the page is loaded, you can use the Page.IsPostBackproperty. If the Page.IsPostBack property is false, the page is loaded for the first time, if it is true,the page is posted back to the server (i.e. from a button click on a form):

    Sub Page_Loadif Not Page.IsPostBack thenlbl1.Text="The date and time is " & now()

    end ifEnd SubSub Submit(s As Object, e As EventArgs)lbl2.Text="Hello World!"End Sub

    The example above will write the "The date and time is...." message only the first time the page isloaded. When a user clicks on the Submit button, the submit subroutine will write "Hello World!" tothe second label, but the date and time in the first label will not change.

    Example:

    ASPX Source:

    Sub Page_Loadif Not Page.IsPostBack then

    lbl1.Text="The date and time is & now()

  • 8/8/2019 ASP W3schools

    13/100

    end if

    End Sub

    Sub Submit(s As Object, e As EventArgs)

    lbl2.Text="Hello World!"End Sub

    Output Result:

    The date and time is 3/10/2007 1:41:21 PM

    Submit

    ASP.NET Web Forms

    All server controls must appear within a tag, and the tag must contain

    the runat="server" attribute.

    ASP.NET Web Forms

    All server controls must appear within a tag, and the tag must contain therunat="server" attribute. The runat="server" attribute indicates that the form should be processedon the server. It also indicates that the enclosed controls can be accessed by server scripts:

    ...HTML + server controls

    Note: The form is always submitted to the page itself. If you specify an action attribute, it is

    ignored. If you omit the method attribute, it will be set to method="post" by default. Also, if you donot specify the name and id attributes, they are automatically assigned by ASP.NET.

  • 8/8/2019 ASP W3schools

    14/100

    Note: An .aspx page can only contain ONE control!

    If you select view source in an .aspx page containing a form with no name, method, action, or idattribute specified, you will see that ASP.NET has added these attributes to the form. It lookssomething like this:

    ...some code

    Submitting a Form

    A form is most often submitted by clicking on a button. The Button server control in ASP.NET hasthe following format:

    The id attribute defines a unique name for the button and the text attribute assigns a label to thebutton. The onClick event handler specifies a named subroutine to execute.

    In the following example we declare a Button control in an .aspx file. A button click runs asubroutine which changes the text on the button:

    Example:

    ASPX Source:

    Sub submit (Source As Object, e As EventArgs)

    button1.Text="You clicked me!"End Sub

    Output Result:

    Click me!

    ASP .NET Maintaining the ViewState

    You may save a lot of coding by maintaining the ViewState of the objects in your WebForm.

    Maintaining the ViewState

  • 8/8/2019 ASP W3schools

    15/100

    When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted aform with a lot of information and the server comes back with an error. You will have to go back tothe form and correct the information. You click the back button, and what happens.......ALL formvalues are CLEARED, and you will have to start all over again! The site did not maintain yourViewState.

    When a form is submitted in ASP .NET, the form reappears in the browser window together with allform values. How come? This is because ASP .NET maintains your ViewState. The ViewStateindicates the status of the page when submitted to the server. The status is defined through ahidden field placed on each page with a control. The source could looksomething like this:

    .....some code

    Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOTmaintain the ViewState, include the directive at the top ofan .aspx page or add the attribute EnableViewState="false" to any control.

    Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on thesubmit button, the form value will disappear:

    Your name:

    Example

    ASPX Source:

    Your name:

  • 8/8/2019 ASP W3schools

    16/100

    Output Result:

    Your name:Submit

    Here is the new ASP .NET way. When you click on the submit button, the form value will NOTdisappear:

    Sub submit(sender As Object, e As EventArgs)lbl1.Text="Hello " & txt1.Text & "!"End SubYour name:

    Example:

    (Click view source in the right frame of the example to see that ASP .NET has added a hidden fieldin the form to maintain the ViewState)

    ASPX Source:

    Sub submit(sender As Object, e As EventArgs)

    lbl1.Text="Hello " & txt1.Text & "!"End Sub

    Your name:

    Output Result:

    Your name:Submit

    ASP .NET - The TextBox Control

    The TextBox control is used to create a text box where the user can input text.

  • 8/8/2019 ASP W3schools

    17/100

    The TextBox Control

    The TextBox control is used to create a text box where the user can input text.

    The example below demonstrates some of the attributes you may use with the TextBox control:

    Example

    ASPX Source:

    A basic TextBox:



    A password TextBox:



    A TextBox with text:

    A multiline TextBox:



    A TextBox with height:

    A TextBox with width:

    Output Result:

    A basic TextBox:

    A password TextBox:

    A TextBox with text:

    A multiline TextBox:

    A TextBox with height:

    A TextBox with width:

  • 8/8/2019 ASP W3schools

    18/100

    Add a Script

    The contents and settings of a TextBox control may be changed by server scripts when a form issubmitted. A form can be submitted by clicking on a button or when a user changes the value in theTextBox control.

    In the following example we declare one TextBox control, one Button control, and one Label controlin an .aspx file. When the submit button is triggered, the submit subroutine is executed. The submitsubroutine writes a text to the Label control:

    Sub submit(sender As Object, e As EventArgs)lbl1.Text="Your name is " & txt1.TextEnd SubEnter your name:

    Example:

    ASPX Source:

    A basic TextBox:



    A password TextBox:

    A TextBox with text:

    A multiline TextBox:

    A TextBox with height:

    A TextBox with width:

  • 8/8/2019 ASP W3schools

    19/100

    Sub submit(sender As Object, e As EventArgs)

    lbl1.Text="Your name is " & txt1.TextEnd Sub

    Enter your name:

    Output Result:

    Enter your name:Submit

    In the following example we declare one TextBox control and one Label control in an .aspx file.When you change the value in the TextBox and either click outside the TextBox or press the Tabkey, the change subroutine is executed. The submit subroutine writes a text to the Label control:

    Sub change(sender As Object, e As EventArgs)lbl1.Text="You changed text to " & txt1.TextEnd SubEnter your name:

    Example:

    ASPX Source:Sub change(sender As Object, e As EventArgs)

    lbl1.Text="You changed text to " & txt1.TextEnd Sub

    Change text

  • 8/8/2019 ASP W3schools

    20/100

    Output Result:

    Change text

    ASP.NET - The Button Control

    The Button control is used to display a push button.

    The Button Control

    The Button control is used to display a push button. The push button may be a submit button or acommand button. By default, this control is a submit button.

    A submit button does not have a command name and it posts the page back to the server when it isclicked. It is possible to write an event handler to control the actions performed when the submitbutton is clicked.A command button has a command name and allows you to create multiple Buttoncontrols on a page. It is possible to write an event handler to control the actions performed whenthe command button is clicked.

    The example below demonstrates a simple Button control:

    Add a Script

    A form is most often submitted by clicking on a button.

    In the following example we declare one TextBox control, one Button control, and one Label controlin an .aspx file. When the submit button is triggered, the submit subroutine is executed. The submitsubroutine writes a text to the Label control:

    Sub submit(sender As Object, e As EventArgs)lbl1.Text="Your name is " & txt1.TextEnd SubEnter your name:

  • 8/8/2019 ASP W3schools

    21/100

    Example:

    ASPX Source:

    Sub submit(sender As Object, e As EventArgs)lbl1.Text="Your name is " & txt1.Text

    End Sub

    Enter your name:

    Output Result:

    Enter your name:Submit

    ASP.NET - Data Binding

    We may use data binding to fill lists with selectable items from an imported data source,like a database, an XML file, or a script.

    Data Binding

    The following controls are list controls which support data binding:

    asp:RadioButtonList

    asp:CheckBoxList

    asp:DropDownList

    asp:Listbox

  • 8/8/2019 ASP W3schools

    22/100

    The selectable items in each of the above controls are usually defined by one or more asp:ListItemcontrols, like this:

    However, with data binding we may use a separate source, like a database, an XML file, or a scriptto fill the list with selectable items.

    By using an imported source, the data is separated from the HTML, and any changes to the itemsare made in the separate data source.

    ASP.NET - The Array List Object

    The ArrayList object is a collection of items containing a single data value.

    Examples

    Example - ArrayList RadioButtonList

    ASPX Source:

    Sub Page_Load

    if Not Page.IsPostBack thendim mycountries=New ArrayList

    mycountries.Add("Norway")mycountries.Add("Sweden")

    mycountries.Add("France")mycountries.Add("Italy")

    mycountries.TrimToSize()mycountries.Sort()

    rb.DataSource=mycountriesrb.DataBind()

    end ifend sub

    sub displayMessage(s as Object,e As EventArgs)

    lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub

  • 8/8/2019 ASP W3schools

    23/100

    Output Result:

    France

    Italy

    Norway

    Sweden

    Example - ArrayList DropDownList

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycountries=New ArrayListmycountries.Add("Norway")

    mycountries.Add("Sweden")mycountries.Add("France")

    mycountries.Add("Italy")mycountries.TrimToSize()

    mycountries.Sort()dd.DataSource=mycountries

    dd.DataBind()end if

    end sub

    sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & dd.SelectedItem.Text

    end sub

    Output Result:

  • 8/8/2019 ASP W3schools

    24/100

    Create an ArrayList

    The ArrayList object is a collection of items containing a single data value.

    Items are added to the ArrayList with the Add() method.

    The following code creates a new ArrayList object named mycountries and four items are added:

    Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New ArrayListmycountries.Add("Norway")mycountries.Add("Sweden")mycountries.Add("France")mycountries.Add("Italy")

    end ifend sub

    By default, an ArrayList object contains 16 entries. An ArrayList can be sized to its final size with the

    TrimToSize() method:

    Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New ArrayListmycountries.Add("Norway")mycountries.Add("Sweden")mycountries.Add("France")mycountries.Add("Italy")mycountries.TrimToSize()

    end ifend sub

    An ArrayList can also be sorted alphabetically or numerically with the Sort() method:

    Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New ArrayListmycountries.Add("Norway")mycountries.Add("Sweden")mycountries.Add("France")mycountries.Add("Italy")mycountries.TrimToSize()mycountries.Sort()

    end ifend sub

    To sort in reverse order, apply the Reverse() method after the Sort() method:

    Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New ArrayListmycountries.Add("Norway")mycountries.Add("Sweden")mycountries.Add("France")

    mycountries.Add("Italy")

  • 8/8/2019 ASP W3schools

    25/100

    mycountries.TrimToSize()mycountries.Sort()mycountries.Reverse()

    end ifend sub

    Data Binding to an ArrayList

    An ArrayList object may automatically generate the text and values to the following controls:

    asp:RadioButtonList

    asp:CheckBoxList

    asp:DropDownList

    asp:Listbox

    To bind data to a RadioButtonList control, first create a RadioButtonList control (without anyasp:ListItem elements) in an .aspx page:

    Then add the script that builds the list and binds the values in the list to the RadioButtonListcontrol:

    Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New ArrayListmycountries.Add("Norway")mycountries.Add("Sweden")mycountries.Add("France")mycountries.Add("Italy")mycountries.TrimToSize()mycountries.Sort()rb.DataSource=mycountriesrb.DataBind()

    end ifend sub

    The DataSource property of the RadioButtonList control is set to the ArrayList and it defines thedata source of the RadioButtonList control. The DataBind() method of the RadioButtonList controlbinds the data source with the RadioButtonList control.

    Note: The data values are used as both the Text and Value properties for the control. To add Valuesthat are different from the Text, use either the Hashtable object or the SortedList object.

  • 8/8/2019 ASP W3schools

    26/100

    ASP.NET - The Hashtable Object

    The Hashtable object contains items in key/value pairs.

    Examples

    Example - Hashtable RadioButtonList

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycountries=New Hashtablemycountries.Add("N","Norway")

    mycountries.Add("S","Sweden")

    mycountries.Add("F","France")mycountries.Add("I","Italy")rb.DataSource=mycountries

    rb.DataValueField="Key"rb.DataTextField="Value"

    rb.DataBind()end if

    end sub

    sub displayMessage(s as Object,e As EventArgs)

    lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub

    Output Result:

    Norway

    Italy

    Sweden

    France

    Example - Hashtable RadiobuttonList

    ASPX Source:

  • 8/8/2019 ASP W3schools

    27/100

    sub Page_Load

    if Not Page.IsPostBack thendim navigate=New Hashtable

    navigate.Add("RadioButtonList","control_radiobuttonlist.asp")navigate.Add("CheckBoxList","control_checkboxlist.asp")

    navigate.Add("DropDownList","control_dropdownlist.asp")

    navigate.Add("ListBox","control_listbox.asp")rb.DataSource=navigaterb.DataValueField="Value"

    rb.DataTextField="Key"rb.DataBind()

    end ifend sub

    sub navigate(s as Object, e As EventArgs)

    response.redirect(rb.SelectedItem.Value)end sub

    Output Result:

    DropDownList

    RadioButtonList

    CheckBoxList

    ListBox

    Example - Hashtable DropDownList

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycountries=New Hashtablemycountries.Add("N","Norway")

    mycountries.Add("S","Sweden")mycountries.Add("F","France")

    mycountries.Add("I","Italy")

    dd.DataSource=mycountries

  • 8/8/2019 ASP W3schools

    28/100

    dd.DataValueField="Key"

    dd.DataTextField="Value"

    dd.DataBind()end if

    end sub

    sub displayMessage(s as Object,e As EventArgs)

    lbl1.text="Your favorite country is: " & dd.SelectedItem.Textend sub

    Output Result:

    Create a Hashtable

    The Hashtable object contains items in key/value pairs. The keys are used as indexes, and veryquick searches can be made for values by searching through their keys.

    Items are added to the Hashtable with the Add() method.

    The following code creates a Hashtable named mycountries and four elements are added:

    Sub Page_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")

    end ifend sub

    Data Binding

    A Hashtable object may automatically generate the text and values to the following controls:

  • 8/8/2019 ASP W3schools

    29/100

    asp:RadioButtonList

    asp:CheckBoxList

    asp:DropDownList

    asp:Listbox

    To bind data to a RadioButtonList control, first create a RadioButtonList control (without anyasp:ListItem elements) in an .aspx page:

    Then add the script that builds the list:

    sub Page_Loadif Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb.DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()

    end ifend sub

    Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonListcontrol. When a radio button is clicked, a text will appear in a label:

    sub Page_Load

    if Not Page.IsPostBack thendim mycountries=New Hashtablemycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb.DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()

    end ifend subsub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Text

    end sub

  • 8/8/2019 ASP W3schools

    30/100

    Note: You cannot choose the sort order of the items added to the Hashtable. To sort itemsalphabetically or numerically, use the SortedList object.

    ASP.NET - The Sorted List Object

    The SortedList object combines the features of both the ArrayList object and the

    Hashtable object.

    Examples

    Example - SortedList RadioButtonList

    ASPX Source:

    sub Page_Load

    if Not Page.IsPostBack thendim mycountries=New SortedList

    mycountries.Add("N","Norway")mycountries.Add("S","Sweden")

    mycountries.Add("F","France")mycountries.Add("I","Italy")

    rb.DataSource=mycountriesrb.DataValueField="Key"

    rb.DataTextField="Value"rb.DataBind()

    end ifend sub

    sub displayMessage(s as Object,e As EventArgs)

    lbl1.text="Your favorite country is: " & rb.SelectedItem.Text

    end sub

  • 8/8/2019 ASP W3schools

    31/100

    Output Result:

    France

    Italy

    Norway

    Sweden

    Example - SortedList RadiobuttonList

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim navigate=New SortedListnavigate.Add("RadioButtonList","control_radiobuttonlist.asp")

    navigate.Add("CheckBoxList","control_checkboxlist.asp")navigate.Add("DropDownList","control_dropdownlist.asp")

    navigate.Add("ListBox","control_listbox.asp")rb.DataSource=navigate

    rb.DataValueField="Value"rb.DataTextField="Key"

    rb.DataBind()end if

    end sub

    sub navigate(s as Object, e As EventArgs)response.redirect(rb.SelectedItem.Value)

    end sub

    Output Result:

    CheckBoxList

    DropDownList

  • 8/8/2019 ASP W3schools

    32/100

    ListBox

    RadioButtonList

    Example - SortedList DropDownList

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycountries=New SortedListmycountries.Add("N","Norway")

    mycountries.Add("S","Sweden")mycountries.Add("F","France")

    mycountries.Add("I","Italy")dd.DataSource=mycountries

    dd.DataValueField="Key"dd.DataTextField="Value"

    dd.DataBind()end if

    end sub

    sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & dd.SelectedItem.Text

    end sub

    Output Result:

    The SortedList Object

    The SortedList object contains items in key/value pairs. A SortedList object automatically sort theitems in alphabetic or numeric order.

    Items are added to the SortedList with the Add() method. A SortedList can be sized to its final sizewith the TrimToSize() method.

    The following code creates a SortedList named mycountries and four elements are added:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycountries=New SortedList

  • 8/8/2019 ASP W3schools

    33/100

    mycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")

    end ifend sub

    Data Binding

    A SortedList object may automatically generate the text and values to the following controls:

    asp:RadioButtonList

    asp:CheckBoxList

    asp:DropDownList

    asp:Listbox

    To bind data to a RadioButtonList control, first create a RadioButtonList control (without anyasp:ListItem elements) in an .aspx page:

    Then add the script that builds the list:

    sub Page_Load

    if Not Page.IsPostBack thendim mycountries=New SortedListmycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb.DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()

    end ifend sub

    Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonListcontrol. When a radio button is clicked, a text will appear in a label:

    sub Page_Load

    if Not Page.IsPostBack thendim mycountries=New SortedList

  • 8/8/2019 ASP W3schools

    34/100

    mycountries.Add("N","Norway")mycountries.Add("S","Sweden")mycountries.Add("F","France")mycountries.Add("I","Italy")rb.DataSource=mycountriesrb.DataValueField="Key"rb.DataTextField="Value"rb.DataBind()

    end ifend subsub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub

    ASP .NET - XML Files

    We can bind an XML file to a list control.

    Examples

    Example - XML RadiobuttonList

    ASPX Source:

    sub Page_Load

    if Not Page.IsPostBack thendim mycountries=New DataSet

    mycountries.ReadXml(MapPath("countries.xml"))rb.DataSource=mycountries

    rb.DataValueField="value"rb.DataTextField="text"

    rb.DataBind()end if

    end sub

    sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Text

    end sub

  • 8/8/2019 ASP W3schools

    35/100

    Output Result:

    Norway

    Sweden

    France

    Italy

    An XML File

    Here is an XML file named "countries.xml":

    NorwayN

    SwedenSFranceFItalyI

    Take a look at the XML file: countries.xml

    Bind a DataSet to a List Control

    First, import the "System.Data" namespace. We need this namespace to work with DataSet objects.Include the following directive at the top of an .aspx page:

    Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is firstloaded:

  • 8/8/2019 ASP W3schools

    36/100

    sub Page_Loadif Not Page.IsPostBack thendim mycountries=New DataSetmycountries.ReadXml(MapPath("countries.xml"))

    end ifend sub

    To bind the DataSet to a RadioButtonList control, first create a RadioButtonList control (without anyasp:ListItem elements) in an .aspx page:

    Then add the script that builds the XML DataSet:

    sub Page_Loadif Not Page.IsPostBack thendim mycountries=New DataSetmycountries.ReadXml(MapPath("countries.xml"))rb.DataSource=mycountriesrb.DataValueField="value"

    rb.DataTextField="text"rb.DataBind()end ifend sub

    Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonListcontrol. When a radio button is clicked, a text will appear in a label:

    sub Page_Loadif Not Page.IsPostBack thendim mycountries=New DataSetmycountries.ReadXml(MapPath("countries.xml"))rb.DataSource=mycountriesrb.DataValueField="value"rb.DataTextField="text"rb.DataBind()

    end if

    end sub

  • 8/8/2019 ASP W3schools

    37/100

    sub displayMessage(s as Object,e As EventArgs)lbl1.text="Your favorite country is: " & rb.SelectedItem.Textend sub

    ASP.NET - The Repeater Control

    The Repeater control is used to display a repeated list of items that are bound to thecontrol.

    Examples

    Repeater control

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))

    cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end ifend sub

  • 8/8/2019 ASP W3schools

    38/100

    Title

    Artist

    CompanyPrice

    Output Result:

    Title Artist Company Price

    Empire Burlesque Bob Dylan Columbia 10.90

    Hide your heart Bonnie Tyler CBS Records 9.90

    Greatest Hits Dolly Parton RCA 9.90

    Still got the blues Gary Moore Virgin records 10.20

    Eros Eros Ramazzotti BMG 9.90

    Repeater control with

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycdcatalog=New DataSet

    mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalog

    cdcatalog.DataBind()end if

    end sub

  • 8/8/2019 ASP W3schools

    39/100

    TitleArtist

    Company

    Price

    Output Result:

    Title Artist Company Price

    Empire Burlesque Bob Dylan Columbia 10.90

    Hide your heart Bonnie Tyler CBS Records 9.90

    Greatest Hits Dolly Parton RCA 9.90

    Still got the blues Gary Moore Virgin records 10.20Eros Eros Ramazzotti BMG 9.90

    Repeater control with

    ASPX Source:

    sub Page_Load

    if Not Page.IsPostBack then

  • 8/8/2019 ASP W3schools

    40/100

    dim mycdcatalog=New DataSet

    mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))

    cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end ifend sub

    Title

    ArtistCompany

    Price

    Bind a DataSet to a Repeater Control

    The Repeater control is used to display a repeated list of items that are bound to the control. TheRepeater control may be bound to a database table, an XML file, or another list of items. Here wewill show how to bind an XML file to a Repeater control.

    We will use the following XML file in our examples ("cdcatalog.xml"):

  • 8/8/2019 ASP W3schools

    41/100

    Empire BurlesqueBob DylanUSAColumbia10.90

    1985Hide your heartBonnie TylerUKCBS Records9.901988Greatest HitsDolly PartonUSARCA9.901982Still got the bluesGary MooreUKVirgin records10.201990ErosEros Ramazzotti

    EUBMG9.901997

    Take a look at the XML file: cdcatalog.xml

    -

    title>Empire Burlesque

    artist>Bob Dylancountry>USA

    company>Columbia

    price>10.90year>1985

    title>Hide your heart

    artist>Bonnie Tylercountry>UK

    company>CBS Recordsprice>9.90

    year>1988

    title>Greatest Hits

    artist>Dolly Partoncountry>USA

    company>RCAprice>9.90

    year>1982

    title>Still got the blues

    artist>Gary Moore

    country>UKcompany>Virgin recordsprice>10.20

    year>1990

    title>Eros

    artist>Eros Ramazzotticountry>EU

    company>BMGprice>9.90

    year>1997

    http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23http://www.w3schools.com/aspnet/cdcatalog.xml#%23
  • 8/8/2019 ASP W3schools

    42/100

    First, import the "System.Data" namespace. We need this namespace to work with DataSet objects.Include the following directive at the top of an .aspx page:

    Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is firstloaded:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))

    end ifend sub

    Then we create a Repeater control in an .aspx page. The contents of the element are rendered first and only once within the output, then the contents of the element are repeated for each "record" in the DataSet, and last, the contents ofthe element are rendered once within the output:

    .........

  • 8/8/2019 ASP W3schools

    43/100

    Then we add the script that creates the DataSet and binds the mycdcatalog DataSet to the Repeatercontrol. We also fill the Repeater control with HTML tags and bind the data items to the cells inthe section with the method:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end ifend sub

    TitleArtistCountryCompanyPriceYear

    Using the

    You can add an element after the element to describethe appearance of alternating rows of output. In the following example each other row in the tablewill be displayed in a light grey color:

    sub Page_Loadif Not Page.IsPostBack thendim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end if

    end sub

  • 8/8/2019 ASP W3schools

    44/100

    Title

    ArtistCountryCompanyPriceYear

    Using the

    The element can be used to describe a separator between each record. Thefollowing example inserts a horizontal line between each table row:

    sub Page_Loadif Not Page.IsPostBack thendim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end ifend sub

  • 8/8/2019 ASP W3schools

    45/100

    TitleArtistCountryCompanyPriceYear

    ASP.NET - The DataList Control

    The DataList control is, like the Repeater control, used to display a repeated list of itemsthat are bound to the control. However, the DataList control adds a table around the dataitems by default.

    Examples

    DataList control

    ASPX Source:

    sub Page_Load

    if Not Page.IsPostBack thendim mycdcatalog=New DataSet

    mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalog

    cdcatalog.DataBind()end if

    end sub

  • 8/8/2019 ASP W3schools

    46/100

    My CD Catalog

    "" of - $

    Hege Refsnes

    Output Result:

    My CD Catalog

    "Empire Burlesque" of Bob Dylan - $10.90

    "Hide your heart" of Bonnie Tyler - $9.90

    "Greatest Hits" of Dolly Parton - $9.90

    "Still got the blues" of Gary Moore - $10.20"Eros" of Eros Ramazzotti - $9.90

    Hege Refsnes

    DataList control with styles

    ASPX Source:

    sub Page_Loadif Not Page.IsPostBack then

    dim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))

    cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end ifend sub

  • 8/8/2019 ASP W3schools

    47/100

    My CD Catalog

    "" of - $

    Hege Refsnes

    Output Result:

    My CD Catalog

    "Empire Burlesque" of Bob Dylan - $10.90

    "Hide your heart" of Bonnie Tyler - $9.90

    "Greatest Hits" of Dolly Parton - $9.90

    "Still got the blues" of Gary Moore - $10.20

    "Eros" of Eros Ramazzotti - $9.90 Hege Refsnes

    DataList control with

    ASPX Source:

    sub Page_Load

    if Not Page.IsPostBack thendim mycdcatalog=New DataSet

    mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))

    cdcatalog.DataSource=mycdcatalog

  • 8/8/2019 ASP W3schools

    48/100

    cdcatalog.DataBind()

    end if

    end sub

    My CD Catalog

    "" of - $

    "" of - $

    Hege Refsnes

    Output Result:

    My CD Catalog

    "Empire Burlesque" of Bob Dylan - $10.90

    "Hide your heart" of Bonnie Tyler - $9.90

    "Greatest Hits" of Dolly Parton - $9.90

    "Still got the blues" of Gary Moore - $10.20

  • 8/8/2019 ASP W3schools

    49/100

    "Eros" of Eros Ramazzotti - $9.90 Hege Refsnes

    Bind a DataSet to a DataList Control

    The DataList control is, like the Repeater control, used to display a repeated list of items that arebound to the control. However, the DataList control adds a table around the data items by default.

    The DataList control may be bound to a database table, an XML file, or another list of items. Herewe will show how to bind an XML file to a DataList control.

    We will use the following XML file in our examples ("cdcatalog.xml"):

    Empire BurlesqueBob DylanUSAColumbia10.901985

    Hide your heartBonnie TylerUKCBS Records9.901988Greatest HitsDolly PartonUSARCA

    9.901982Still got the bluesGary MooreUKVirgin records10.201990ErosEros Ramazzotti

    EUBMG9.901997

    Take a look at the XML file: cdcatalog.xml

    First, import the "System.Data" namespace. We need this namespace to work with DataSet objects.Include the following directive at the top of an .aspx page:

  • 8/8/2019 ASP W3schools

    50/100

    Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is firstloaded:

    sub Page_Loadif Not Page.IsPostBack thendim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))

    end ifend sub

    Then we create a DataList in an .aspx page. The contents of the element arerendered first and only once within the output, then the contents of the elementare repeated for each "record" in the DataSet, and last, the contents of the element are rendered once within the output:

    .........

    Then we add the script that creates the DataSet and binds the mycdcatalog DataSet to the DataList

    control. We also fill the DataList control with a that contains the header of thetable, an that contains the data items to display, and a thatcontains a text. Note that the gridlines attribute of the DataList is set to "both" to display tableborders:

    sub Page_Loadif Not Page.IsPostBack thendim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end if

    end subMy CD Catalog"" of -$

  • 8/8/2019 ASP W3schools

    51/100

    Copyright Hege Refsnes

    Using Styles

    You can also add styles to the DataList control to make the output more fancy:

    sub Page_Loadif Not Page.IsPostBack thendim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()

    end ifend sub

    My CD Catalog"" of -$

    Copyright Hege Refsnes

    Using the

    You can add an element after the element to describethe appearance of alternating rows of output. You may style the data in the section within the DataList control:

  • 8/8/2019 ASP W3schools

    52/100

    sub Page_Loadif Not Page.IsPostBack thendim mycdcatalog=New DataSetmycdcatalog.ReadXml(MapPath("cdcatalog.xml"))cdcatalog.DataSource=mycdcatalogcdcatalog.DataBind()end if

    end subMy CD Catalog"" of -$

    "" of -$ Hege Refsnes

    ASP.NET - Database Connection

    ADO.NET is also a part of the .NET Framework. ADO.NET is used to handle data access.

    With ADO.NET you can work with databases.

    Examples

    Database connection - Bind to a Repeater control

  • 8/8/2019 ASP W3schools

    53/100

    ASPX Source:

    sub Page_Loaddim dbconn,sql,dbcomm,dbread

    dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" &

    server.mappath("/db/northwind.mdb"))dbconn.Open()

    sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)

    dbread=dbcomm.ExecuteReader()customers.DataSource=dbread

    customers.DataBind()dbread.Close()

    dbconn.Close()end sub

    Companyname

    Contactname

    AddressCity

  • 8/8/2019 ASP W3schools

    54/100

    Output Result:

    Companyname Contactname Address City

    Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin

    Berglunds snabbkp Christina Berglund Berguvsvgen 8 Lule

    Centro comercial

    MoctezumaFrancisco Chang

    Sierras de Granada

    9993Mxico D.F.

    Ernst Handel Roland Mendel Kirchgasse 6 Graz

    FISSA Fabrica Inter.Salchichas S.A.

    Diego Roel C/ Moralzarzal, 86 Madrid

    Galera del gastrnomo Eduardo SaavedraRambla de Catalua,23

    Barcelona

    Island Trading Helen BennettGarden HouseCrowther Way

    Cowes

    Kniglich Essen Philip Cramer Maubelstr. 90 Brandenburg

    Laughing Bacchus WineCellars Yoshi Tannamuri 1900 Oak St. Vancouver

    Magazzini AlimentariRiuniti

    Giovanni RovelliVia Ludovico il Moro22

    Bergamo

    North/South Simon CrowtherSouth House 300Queensbridge

    London

    Paris spcialits Marie Bertrand265, boulevardCharonne

    Paris

    Rattlesnake CanyonGrocery

    Paula Wilson 2817 Milton Dr. Albuquerque

    Simons bistro Jytte Petersen Vinbltet 34 Kbenhavn

    The Big Cheese Liz Nixon89 Jefferson Way Suite2

    Portland

    Vaffeljernet Palle Ibsen Smagslget 45 rhus

    Wolski ZajazdZbyszekPiestrzeniewicz

    ul. Filtrowa 68 Warszawa

    Database connection - Bind to a DataList control

    ASPX Source:

    sub Page_Load

    dim dbconn,sql,dbcomm,dbreaddbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" &

    server.mappath("/db/northwind.mdb"))dbconn.Open()

    sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)

    dbread=dbcomm.ExecuteReader()

  • 8/8/2019 ASP W3schools

    55/100

    customers.DataSource=dbread

    customers.DataBind()

    dbread.Close()dbconn.Close()

    end sub

    Customers Table

    in

    ,

    Source: Northwind Database

    Output Result:

    Customers Table

    Alfreds Futterkiste in Obere Str. 57, Berlin

    Berglunds snabbkp in Berguvsvgen 8, Lule

    Centro comercial Moctezuma in Sierras de Granada 9993, Mxico D.F.

    Ernst Handel in Kirchgasse 6, Graz

    FISSA Fabrica Inter. Salchichas S.A. in C/ Moralzarzal, 86, Madrid

    Galera del gastrnomo in Rambla de Catalua, 23, Barcelona

    Island Trading in Garden House Crowther Way, Cowes

  • 8/8/2019 ASP W3schools

    56/100

    Kniglich Essen in Maubelstr. 90, Brandenburg

    Laughing Bacchus Wine Cellars in 1900 Oak St., Vancouver

    Magazzini Alimentari Riuniti in Via Ludovico il Moro 22, Bergamo

    North/South in South House 300 Queensbridge, London

    Paris spcialits in 265, boulevard Charonne, Paris

    Rattlesnake Canyon Grocery in 2817 Milton Dr., AlbuquerqueSimons bistro in Vinbltet 34, Kbenhavn

    The Big Cheese in 89 Jefferson Way Suite 2, Portland

    Vaffeljernet in Smagslget 45, rhus

    Wolski Zajazd in ul. Filtrowa 68, WarszawaSource: Northwind Database

    What is ADO.NET?

    ADO.NET is a part of the .NET Framework

    ADO.NET consists of a set of classes used to handle data access

    ADO.NET is entirely based on XML ADO.NET has, unlike ADO, no Recordset object

    Create a Database Connection

    We are going to use the Northwind database in our examples.

    First, import the "System.Data.OleDb" namespace. We need this namespace to work with MicrosoftAccess and other OLE DB database providers. We will create the connection to the database in thePage_Load subroutine. We create a dbconn variable as a new OleDbConnection class with aconnection string which identifies the OLE DB provider and the location of the database. Then weopen the database connection:

    sub Page_Loaddim dbconndbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))dbconn.Open()end sub

    Note: The connection string must be a continuous string without a line break!

    Create a Database Command

    To specify the records to retrieve from the database, we will create a dbcomm variable as a newOleDbCommand class. The OleDbCommand class is for issuing SQL queries against database tables:

    sub Page_Loaddim dbconn,sql,dbcommdbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))dbconn.Open()sql="SELECT * FROM customers"

    dbcomm=New OleDbCommand(sql,dbconn)

  • 8/8/2019 ASP W3schools

    57/100

    end sub

    Create a DataReader

    The OleDbDataReader class is used to read a stream of records from a data source. A DataReader iscreated by calling the ExecuteReader method of the OleDbCommand object:

    sub Page_Loaddim dbconn,sql,dbcomm,dbreaddbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))dbconn.Open()sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)dbread=dbcomm.ExecuteReader()end sub

    Bind to a Repeater Control

    Then we bind the DataReader to a Repeater control:

    sub Page_Loaddim dbconn,sql,dbcomm,dbreaddbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=" & server.mappath("northwind.mdb"))

    dbconn.Open()sql="SELECT * FROM customers"dbcomm=New OleDbCommand(sql,dbconn)dbread=dbcomm.ExecuteReader()customers.DataSource=dbreadcustomers.DataBind()dbread.Close()dbconn.Close()end sub

    CompanynameContactnameAddressCity

  • 8/8/2019 ASP W3schools

    58/100

    Close the Database Connection

    Always close both the DataReader and database connection after access to the database is nolonger required:

    dbread.Close()

    dbconn.Close()

    HTML Server Controls

    HTML server controls are HTML tags understood by the server.

    HTML Server Controls

    HTML elements in ASP.NET files are, by default, treated as text. To make these elementsprogrammable, add a runat="server" attribute to the HTML element. This attribute indicates that

    the element should be treated as a server control.

    Note: All HTML server controls must be within a tag with the runat="server" attribute!

    Note: ASP.NET requires that all HTML elements must be properly closed and properly nested.

    HTML Server Control Description

    HtmlAnchor Controls an HTML element

    HtmlButton Controls a HTML element

    HtmlForm Controls a HTML element

    HtmlGeneric Controls other HTML element not specified by a specific HTML servercontrol, like , , , etc.

    HtmlImage Controls an HTML elementHtmlInputButton Controls , , and HTML elements

    HtmlInputCheckBox Controls an HTML element

    HtmlInputFile Controls an HTML element

    HtmlInputHidden Controls an HTML element

    HtmlInputImage Controls an HTML element

    HtmlInputRadioButton Controls an HTML element

    HtmlInputText Controls and HTMLelements

    HtmlSelect Controls a HTML element

    HtmlTable Controls a HTML element

    HtmlTableCell Controls and HTML elementsHtmlTableRow Controls a HTML element

  • 8/8/2019 ASP W3schools

    59/100

    HtmlTextArea Controls a HTML element

    ASP.NET HtmlAnchor Control

    Definition and Usage

    The HtmlAnchor control is used to control an element. In HTML, the element is used tocreate a hyperlink. The hyperlink may link to a bookmark or to another Web page.

    Properties

    Property Description

    Attributes Returns all attribute name and value pairs of the element

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    HRef The URL target of the link

    id A unique id for the control

    InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not automatically convertedto HTML entities

    InnerText Sets or returns all text between the opening and closing tags of theHTML element. Special characters are automatically converted to HTMLentities

    Name The name of the anchorOnServerClick The name of the function to be executed when the link is clicked

    runat Specifies that the control is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Target The target window to open

    Title A title to be displayed by the browser (like the alt attribute of the imgelement)

    Visible A Boolean value that indicates whether or not the control should bevisible

    Example

    HTMLAnchor

    ASPX Source:

    Sub Page_Load

    link1.HRef="http://www.w3schools.com"link1.Target="_blank"

    link1.Title="W3Schools"

    link2.HRef="http://www.microsoft.com"

    link2.Target="_blank"

    link2.Title="Microsoft"

  • 8/8/2019 ASP W3schools

    60/100

    End Sub

    Visit W3Schools!
    Visit Microsoft!

    Output Result:

    Visit W3Schools!Visit Microsoft

    In this example we declare two HtmlAnchor controls in an .aspx file (remember to embed thecontrol inside an HtmlForm control). Then we modify the URL, target, and title of the HtmlAnchorcontrols in an event handler (an event handler is a subroutine that executes code for a givenevent). The Page_Load event is one of many events that ASP .NET understands.

    ASP.NET HtmlButton Control

    Definition and Usage

    The HtmlButton control is used to control a element. In HTML, the element isused to create a push button.

    Properties

    Property Description

    Attributes Returns all attribute name and value pairs of the element

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    id A unique id for the control

    InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not automatically convertedto HTML entities

    InnerText Sets or returns all text between the opening and closing tags of theHTML element. Special characters are automatically converted to HTMLentities

    OnServerClick The name of the function to be executed when the button is clickedrunat Specifies that the control is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Visible A Boolean value that indicates whether or not the control should bevisible

    Example

    HTMLButton

    ASPX Source:

  • 8/8/2019 ASP W3schools

    61/100

    Sub button1(Source As Object, e As EventArgs)p1.InnerHtml="You clicked the blue button!"

    End Sub

    Sub button2(Source As Object, e As EventArgs)p1.InnerHtml="You clicked the pink button!"

    End Sub

    Blue button!

    Pink button!

    Output Result:

    !!

    In this example we declare two HtmlButton controls in an .aspx file (remember to embed thecontrol inside an HtmlForm control). Next, we write an event handler that specifies what to happenwhen a button is clicked.

    ASP.NET HtmlForm Control

    Definition and Usage

    The HtmlForm control is used to control a element. In HTML, the element is used

    to create a form.

    Note: All HTML server controls must be within the HtmlForm control!

    Note: You can only have one HtmlForm control on a single page!

    Properties

    Property Description

    Action A URL that defines where to send the data when the form is submitted.

    Note: This attribute is always set to the URL of the page itself!

    Attributes Returns all attribute name and value pairs of the element

    Blue button Pink Button

  • 8/8/2019 ASP W3schools

    62/100

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    EncType The mime type used to encode the content of the form

    id A unique id for the control

    InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not automatically convertedto HTML entities

    InnerText Sets or returns all text between the opening and closing tags of the

    HTML element. Special characters are automatically converted to HTMLentities

    Method How the form posts data to the server. Legal values are: "post" and"get". Default is "post"

    Name The name of the form

    runat Specifies that the control is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Target The target window to load the URL

    Visible A Boolean value that indicates whether or not the control should bevisible

    Example

    HTMLForm

    ASPX Source:Sub submit(sender As Object, e as EventArgs)

    if name.value"" thenp1.InnerHtml="Welcome " & name.value & "!"

    end ifEnd Sub

    Enter your name:

    Output Result:

    Enter your name:

    Submit

    In this example we declare one HtmlInputText controls, one HtmlInputButton control, and oneHtmlGeneric control in an .aspx file (remember to embed the controls inside an HtmlForm control).When the submit button is triggered, the submit subroutine is executed. The submit subroutinewrites a welcome message to the p element.

  • 8/8/2019 ASP W3schools

    63/100

    ASP.NET HtmlGeneric Control

    Definition and Usage

    The HtmlGeneric control is used to control other HTML element not specified by a specific HTMLserver control, like , , , ,

    , etc.

    Properties

    Property Description

    Attributes Returns all attribute name and value pairs of the element

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    id A unique id for the control

    InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not automatically convertedto HTML entities

    InnerText Sets or returns all text between the opening and closing tags of the

    HTML element. Special characters are automatically converted to HTMLentities

    runat Specifies that the control is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Visible A Boolean value that indicates whether or not the control should bevisible

    Example

    HTMLGeneric

    ASPX Source:

    Sub submit(sender As Object, e as EventArgs)

    if name.value"" thenp1.InnerHtml="Welcome " & name.value & "!"

    end ifEnd Sub

    Enter your name:

    Output Result:

    Enter your name:

  • 8/8/2019 ASP W3schools

    64/100

    Submit

    In this example we declare one HtmlInputText controls, one HtmlInputButton control, and oneHtmlGeneric control (the

    tag) in an .aspx file (remember to embed the controls inside anHtmlForm control). When the submit button is triggered, the submit subroutine is executed. Thesubmit subroutine writes a welcome message to the p element.

    ASP.NET HtmlImage Control

    Definition and Usage

    The HtmlImage control is used to control an element. In HTML, the element is usedto display an image.

    Properties

    Property Description

    Align How to align the image according to surrounding elements. Legalvalues are:

    top

    middle

    bottom

    left

    right

    Alt A short description of the image

    Attributes Returns all attribute name and value pairs of the element

    Border The width of the borders around the image

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    Height The height of the image

    id A unique id for the control

    runat Specifies that the control is a server control. Must be set to "server"

    Src The URL of the image to display

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Visible A Boolean value that indicates whether or not the control should bevisible

    Width The width of the image

    Example

    HTMLImage

    ASPX Source:

    Sub Page_Load(Sender As Object,E As EventArgs)

    image1.Src="smiley.gif"image1.Alt="Smiley"

    image1.Border="3"End Sub

  • 8/8/2019 ASP W3schools

    65/100

    Output Result:

    In this example we declare an HtmlImage control in an .aspx file (remember to embed the controlinside an HtmlForm control). Then we modify the src, alt and border properties of the HtmlImagecontrol in an event handler (an event handler is a subroutine that executes code for a given event).The Page_Load event is one of many events that ASP .NET understands:

    HTMLImage

    ASPX Source:

    Sub choose_image(Sender As Object, e As EventArgs)

    image1.Src = select1.ValueEnd Sub

    Smiley

    AngryStickman



    Output Result

    Display image

    In this example we declare an HtmlImage and an HTMLSelect control in an .aspx file (remember to

    embed the controls inside an HtmlForm control). Then we modify the src property of the HtmlImage

  • 8/8/2019 ASP W3schools

    66/100

    control based on user choices. The value selected in the HtmlSelect control determines which imageto display.

    ASP.NET HtmlInputButton Control

    Definition and Usage

    The HtmlInputButton control is used to control , , and elements. In HTML, these elements are used to create a command button, asubmit button, and a reset button.

    Properties

    Property Description

    Attributes Returns all attribute name and value pairs of the element

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    id A unique id for the element

    Name The name of the element

    OnServerClick The name of the function to be executed when the button is clicked

    runat Specifies that the element is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag nameType The type of the element

    Value The value of the element

    Visible A Boolean value that indicates whether or not the control should bevisible

    Example

    HTMLInputbutton

    In this example we declare one HtmlInputText controls, one HtmlInputButton control, and oneHtmlGeneric control in an .aspx file (remember to embed the controls inside an HtmlForm control).

    When the submit button is triggered, the submit subroutine is executed. The submit subroutinewrites a welcome message to the p element.

    ASP.NET HtmlInputCheckBox Control

    Definition and Usage

    The HtmlInputCheckBox control is used to control an element. In HTML,this element is used to create a checkbox.

    Properties and Events

    Property Description

  • 8/8/2019 ASP W3schools

    67/100

    Attributes Returns all attribute name and value pairs of the element

    Checked A Boolean value that specifies whether or not the element is to bechecked

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    id A unique id for the control

    Name The name of the element

    runat Specifies that the element is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Type The type of the element

    Value The value of the element

    Visible A Boolean value that indicates whether or not the control should bevisible

    Event Description

    ServerChange Occurs when the state of the control has changed

    Example

    HTMLInputCheckbox

    ASPX Source:

    Sub submit(Source As Object, e As EventArgs)

    if red.Checked=True thenp1.InnerHtml="You prefer red!"

    elsep1.InnerHtml="You prefer blue!"

    end ifred.checked=false

    blue.checked=falseEnd Sub

    What color do you prefer?

    Red


    Blue


    Output Result:

    What color do you prefer?

    Red

    Blue

  • 8/8/2019 ASP W3schools

    68/100

    In this example we declare two HtmlInputCheckBox controls, one HtmlInputButton control, and oneHtmlGeneric in an .aspx file (remember to embed the controls inside an HtmlForm control). Whenthe submit button is triggered, the submit subroutine is executed. The submit subroutine mayrespond in two ways: if the "red" checkbox is checked, the server sends the message "You preferred!" to the p element. If the "blue" checkbox is checked, the server sends the message "You preferblue!" to the p element.

    ASP.NET HtmlInputFile ControlDefinition and Usage

    The HtmlInputFile control is used to control an element. In HTML, this elementis used to upload a file to the server.

    Properties

    Property Description

    Accept List of acceptable MIME types

    Attributes Returns all attribute name and value pairs of the element

    Disabled A Boolean value that indicates whether or not the control should be

    disabled. Default is falseid A unique id for the element

    MaxLength The maximum number of characters allowed in this element

    Name The name of the element

    PostedFile Gets access to the posted file

    runat Specifies that the element is a server control. Must be set to "server"

    Size The width of the element

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Type The type of the element

    Value The value of the element

    Visible A Boolean value that indicates whether or not the control should be

    visible

    Example

    In the following example we declare one HtmlInputFile control, one HtmlInputButton control, andthree HtmlGeneric controls in an .aspx file (remember to embed the controls inside an HtmlFormcontrol). When the submit button is triggered, the submit subroutine is executed. The file name andfile type are displayed on the page, while the file itself is uploaded to the c directory on the server:

    Sub submit(Sender as Object, e as EventArgs)fname.InnerHtml=MyFile.PostedFile.FileNameclength.InnerHtml=MyFile.PostedFile.ContentLength

    MyFile.PostedFile.SaveAs("c:\uploadfile.txt")End Sub

    Select file to upload to server:

  • 8/8/2019 ASP W3schools

    69/100

    FileName:
    ContentLength: bytes

    ASP.NET HtmlInputHidden Control

    Definition and Usage

    The HtmlInputHidden control is used to control an element. In HTML, thiselement is used to create a hidden input field.

    Properties and Events

    Property Description

    Attributes Returns all attribute name and value pairs of the element

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    id A unique id for the element

    Name The name of the element

    runat Specifies that the element is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Type The type of the element

    Value The value of the hidden field

    Visible A Boolean value that indicates whether or not the control should bevisible

    Event DescriptionServerChange When the content of the element has changed

    Example

    HTMLInputHidden

    ASPX Source:

    Sub submit(Source As Object, e As EventArgs)hidden1.Value=string1.Value

    p1.InnerHtml="Hidden value= " + hidden1.Value

    End Sub

    Enter some text:

  • 8/8/2019 ASP W3schools

    70/100

    Output Result:

    Enter some text:Submit

    In this example we declare one HtmlInputHidden control, one HtmlInputText control, one

    HtmlInputButton control, and one HtmlGeneric control in an .aspx file (remember to embed thecontrols inside an HtmlForm control). When the submit button is triggered, the submit subroutine isexecuted. The submit subroutine sets the value of the hidden field equal to value of the input fieldand then displays the value of the hidden field in the p element.

    ASP.NET HtmlInputImage Control

    Definition and Usage

    The HtmlInputImage control is used to control an element. In HTML, thiselement is used to create an input button using an image, instead of a regular push-style button.

    Properties and EventsProperty Description

    Align The alignment of the image

    Alt An alternate text to display for the image

    Attributes Returns all attribute name and value pairs of the element

    Border The width of the borders around the element

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    id A unique id for the control

    Name The name of the element

    OnServerClick The name of the function to be executed when the image is clicked

    runat Specifies that the element is a server control. Must be set to "server"

    Src The source of the image

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Type The type of the element

    Value The value of the element

    Visible A Boolean value that indicates whether or not the control should bevisible

    Example

    HTMLInputImage

    ASPX Source:

    Sub button1(Source As Object, e As ImageClickEventArgs)

    p1.InnerHtml="You clicked the smiley button!"

    End SubSub button2(Source As Object, e As ImageClickEventArgs)

    p1.InnerHtml="You clicked the angry button!"

    End Sub

  • 8/8/2019 ASP W3schools

    71/100

    Click on one of the images:

    Output Result:

    Click on one of the images:

    In this example we declare two HtmlInputImage controls and one HtmlGeneric control in an .aspxfile (remember to embed the controls inside an HtmlForm control). If the user clicks on the firstimage, the button1 subroutine is executed. This subroutine sends the message "You clicked thesmiley button!" to the p element. If the user clicks on the second image, the button2 subroutine isexecuted. This subroutine sends the message "You clicked the angry button!" to the p element.

    ASP.NET HtmlInputRadioButton Control

    Definition and Usage

    The HtmlInputRadioButton control is used to control an element. In HTML,this element is used to create a radiobutton.

    Properties

    Property Description

    Attributes Returns all attribute name and value pairs of the element

    Checked A Boolean value that specifies whether or not the element is to beselected

    Disabled A Boolean value that indicates whether or not the control should be

    disabled. Default is falseid A unique id for the element

  • 8/8/2019 ASP W3schools

    72/100

    Name The name of the radio button group

    runat Specifies that the element is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Type The type of the element

    Value The value of the element

    Visible A Boolean value that indicates whether or not the control should be

    visible

    Example

    HTMLInputRadiobutton

    ASPX Source:

    Sub submit(Source As Object, e As EventArgs)

    if r1.Checked=True then

    p1.InnerHtml="Your favorite color is red"else

    if r2.Checked=True thenp1.InnerHtml="Your favorite color is green"

    elseif r3.Checked=True then

    p1.InnerHtml="Your favorite color is blue"end if

    end ifend if

    End Sub

    Select your favorite color:


    Red


    Green


    Blue

    Output Result:

    Select your favorite color:

    Red

    Green

  • 8/8/2019 ASP W3schools

    73/100

  • 8/8/2019 ASP W3schools

    74/100

    Enter your name:



    Output Result:

    Enter your name:

    Submit

    In this example we declare one HtmlInputText controls, one HtmlInputButton control, and oneHtmlGeneric control in an .aspx file (remember to embed the controls inside an HtmlForm control).When the submit button is triggered, the submit subroutine is executed. The submit subroutinewrites a welcome message to the p element.

    ASP.NET HtmlSelect Control

    Definition and Usage

    The HtmlSelect control is used to control a element. In HTML, the element isused to create a drop-down list.

    Properties

    Property Description

    Attributes Returns all attribute name and value pairs of the element

    DataMember A name of a data table to use

    DataSource A data source to use

    DataTextField A field in the data source to be displayed in the drop-down list

    DataValueField A field in the data source that specifies the value of each selectableitem in the drop-down list

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    id A unique id for the control

    InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not automatically convertedto HTML entities

    InnerText Sets or returns all text between the opening and closing tags of theHTML element. Special characters are automatically converted to HTMLentities

    Items The list of items in the drop-down list

    Multiple Whether multiple items can be selected at a time

    OnServerChange The name of the function to be executed when the selected item haschanged

    runat Specifies that the control is a server control. Must be set to "server"

    SelectedIndex The index of the currently selected item

    Size The number of visible items in the drop-down list

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Value The value of the currently selected item

    Visible A Boolean value that indicates whether or not the control should bevisible

  • 8/8/2019 ASP W3schools

    75/100

    Example

    HTMLSelect

    ASPX Source:

    Sub choose_image(Sender As Object, e As EventArgs)

    image1.Src = select1.ValueEnd Sub

    SmileyAngry

    Stickman



    Output Result:

    Display image

    In this example we declare an HtmlImage and an HTMLSelect control in an .aspx file (remember toembed the controls inside an HtmlForm control). Then we modify the src property of the HtmlImagecontrol based on user choices. The value selected in the HtmlSelect control determines which imageto display.

    ASP.NET HtmlTable Control

    Definition and Usage

    The HtmlTable control is used to control a element. In HTML, the element is usedto create a table.

    Properties

    Property Description

    Align Specifies the alignment of the table

    Attributes Returns all attribute name and value pairs of the element

    BGColor Specifies the background color of the table

    Border Specifies the width of the borders

  • 8/8/2019 ASP W3schools

    76/100

    Tip: Set border="0" to display tables with no borders!

    BorderColor Specifies the color of the borders

    CellPadding Specifies the space between the cell walls and contents

    CellSpacing Specifies the space between cells

    Disabled A Boolean value that indicates whether or not the control should bedisabled. Default is false

    Height Specifies the height of the tableid A unique id for the control

    InnerHtml Sets or returns the content between the opening and closing tags of the HTML element. Special characters are not automatically convertedto HTML entities

    InnerText Sets or returns all text between the opening and closing tags of theHTML element. Special characters are automatically converted to HTMLentities

    Rows Returns an HtmlRowCollection object which represents all rows in thetable

    runat Specifies that the control is a server control. Must be set to "server"

    Style Sets or returns the CSS properties that are applied to the control

    TagName Returns the element tag name

    Visible A Boolean value that indicates whether or not the control should bevisible

    Width Specifies the width of the table

    Example

    HTMLTable

    ASPX Source:

    Sub submit(sender As Object, e As EventArgs)

    Dim row,numrows,numcells,j,irow=0numrows=cint(rows1.Value)

    numcells=cint(cells1.Value)for j=1 to numrows

    Dim r As New HtmlTableRow()row=row+1

    for i=1 to numcellsDim c As New HtmlTableCell()

    c.Controls.Add(New LiteralControl("row " & j & ", cell " & i))

    r.Cells.Add(c)next

    t1.Rows.Add(r)

    t1.Visible=truenext

    End Sub

    Table rows:

    1

    23

  • 8/8/2019 ASP W3schools

    77/100


    Table cells:

    1

    23



    Output Result:

    Table rows:

    Table cells:

    Display Table

    In this example we declare two HtmlSelect controls, one HtmlInputButton control, and oneHtmlTable control in an .aspx file (remember to embed the controls inside an HtmlForm control).The user may choose number of cells and rows. When the submit button is triggered, the submitsubroutine is executed. The submit subroutine generates the table based on what the user didinput.

    HTMLTable

    ASPX Source:

    Sub submit(sender As Object, e As EventArgs)dim i,j

    table1.BGColor="yellow"table1.BorderColor="red"

    for i=0 To table1.Rows.Count-1for j=0 To table1.Rows(i).Cells.Count-1

    table1.Rows(i).Cells(j).InnerHtml="Row " & inext

    nextEnd Sub

    Cell 1Cell 2

  • 8/8/2019 ASP W3schools

    78/100

  • 8/8/2019 ASP W3schools

    79/100

    Example

    HTMLTable