0% found this document useful (0 votes)
23 views

Note

ASP.net Note

Uploaded by

Tsegaye Hailu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Note

ASP.net Note

Uploaded by

Tsegaye Hailu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

ASP.

NET Server Controls

Major Features of ASP.NET Server Controls

 When you develop an ASP.NET Web Form, you can use the following
type of controls:
a) HTML Server Controls
 You can manipulate these controls at the server-side.
 Before dispatching a form to the client, the ASP Engine converts
them to the equivalent HTML elements.
 These controls are included in the System.Web.UI.HtmlControls
namespace.
b) Web Server Controls/Web Controls/ASP.NET Web Form
Controls)
 These are the new generation’s controls developed by Microsoft.
 In the HTML or .aspx file, these are typically referenced with an
asp: prefix such as asp:Label, asp:Button, or asp:TextBox.
 The ASP.NET Engine also maps these controls to standard HTML
equivalent controls before dispatching the page to the client.
 These Web server controls are available in the
System.Web.UI.WebControls namespace.
c) Validation Controls
 This set of controls provides features for automatically checking the
specified validity of user inputs.
 These controls are available in the System.Web.UI.WebControls
namespace.
d) Custom Controls
 You can develop your own server controls by extending an existing
control or group of controls to provide additional functionalities.
 There are two versions of custom controls:Web User Controls and
Web Custom Controls.
 The Web User Controls are easy to develop, and are typically stored
as .ascx files.
 The Web Custom Controls require in-depth knowledge of Object
Oriented Programming and the Common Language Runtime
(CLR).These are stored in compiled form as assemblies.
 In an IIS environment, the ASP and ASP.NET can run side by side. If you
install ASP.NET, your existing ASP applications will continue running.
The IIS uses the ASP Engine to process the .asp files, whereas it uses the
ASP.NET Engine to process the .aspx files. Session states and
application states are not shared between ASP and ASP.NET pages.
Collecting Data Using HTML Forms

 HTML uses the Hypertext Transfer Protocol (HTTP) to transmit Web


pages.
 When you enter a URL of a page in your browser,
 The browser sends an HTTP message to the server, requesting the
desired page.This message is typically known as the Request
message.
 If the desired page has a *.html or *.htm extension, the Web server
simply retrieves the page from the server’s disk and sends it back to
your computer (client) via a new HTTP message, known as the
Response message.
 It is your browser that interprets the mark-up codes in the Response
object and presents the page on your monitor.
 In an HTML document, you can use an HTML form element to collect
data from the user. When the user click SUMIT button the browser
packages the user’s given data in a HTTP message / Request message
and then sends it to the server.
 The Request message has two parts: the HTTP Header and the HTTP
Body.
 The browser can package the user-given data in the Request object in
one of two ways.
a) It may augment the URL with the name-value pairs of submitted data.
b) It can package the submitted data inside the body part of the Request
message.
 Which of the one the above two alternative methods will it use? The
Method parameter in the HTML form element is used to specify the
mode of data transmission.
 If it is “Get”, the browser sends the data in the header section of the
HTTP message.
 If it is “Post”, the data are sent in the body section.
 The Action parameter can be used to request a specified html or other
documents like .asp or .aspx files.
<form name= "myForm" Action="Sample1.html"
Method="Get">

Server-Side Processing in ASP.NET

 An ASP.NET file has an *.aspx extension. Typically, it contains HTML


elements, server-side codes and client-side codes.
 The major steps in processing a request for an ASPX page are as follows:
1) The server receives a request for a desired ASPX page.
2) The server locates the page in the disk.
3) The server gives the page to the ASP.NET Engine.
4) The ASP.NET Engine compiles the page and generates the page
class.
5) The ASP.NET instantiates the class, performs necessary processing,
and it generates the Response object.
6) The Web server then sends the Response object to the client.

 The ASP.NET engine maps the server controls to standard HTML


controls, and the ASP.NET employs hidden fields to maintain the states
of the controls.
Including Scripts in an .aspx File

 See the following example


<%@ Page Language="VB" debug = "true"%>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server" action="default.aspx">
Please select a flower you like
<br />
<asp:ListBox ID="lstFlower" Rows="3" runat="server">
</asp:ListBox>
<br />
<asp:Button ID="btnShow" Text="Show" OnClick="Show_Selection"
runat="server"/>
<br />
<br />
<asp:Label ID="lblSelection" runat="server"></asp:Label>
</form>
</body>
</html>

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


Sub Page_Load(ByVal source As Object, ByVal e As EventArgs)
lstFlower.Items.Add("Tulip")
lstFlower.Items.Add("Poppy")
lstFlower.Items.Add("Iris")
lstFlower.SelectedIndex = 0
End Sub

Sub Show_Selection(ByVal source As Object, ByVal e As EventArgs)


Me.lblSelection.Text = "You have selected: " +
Me.lstFlower.SelectedItem.Text
End Sub
</script>

 In the above example - First, irrespective of the selection we make, it will


always display “You have selected Tulip”. Secondly, on repeated clicks of
the command button, the list box will continue growing with duplicate
entries. Inorder to solve these problems we use IsPostBack property of
a Page.
 In the previous example, when we click the command button, it submits
the form back to the server and requests the same page.This
phenomenon is known as PostBack. At postBack the Page_Load event
will take place on every request. That is why, the list box will keep on
growing in size.
 In order to solve the above two problems use the following code listing

Sub Page_Load(ByVal source As Object, ByVal e As EventArgs)


If Not Page.IsPostBack Then
lstFlower.Items.Add("Tulip")
lstFlower.Items.Add("Gaye")
lstFlower.Items.Add("Hailu")
lstFlower.SelectedIndex = 0
End If
End Sub

AutoPostBack Attributes of Server Controls

<asp:ListBox ID="lstFlower" Rows="3" runat="server" AutoPostBack="true"


OnSelectedIndexChanged="Show_selection"></asp:ListBox>

 While using the AutoPostBack attribute, we need to be careful. An


AutoPostBack submits the form to the server; thus, the system will
eventually slow down significantly if we use too many of these
AutoPostBacks.
Structure of an ASP.NET Web Form

 A Web Form is an ASP.NET technology that we use to create a


programmable Web page.
 In .NET documentation, Microsoft has outlined the following
characteristics of a Web form:
 A Web form of your design can run on a specific browser of your
choice, or it can run on any browser and automatically render the
browser-compliant HTML.
 It can be programmed in any CLR-supported language.
 It supports WYSIWYG editing tools and development tools such as
VS.NET.
 It supports a rich set of controls that enables you to encapsulate page
logic into reusable components and declaratively handle page events.
 It allows for separation between code and content on a page.
 It provides a set of state management features that preserves the view
state of a page between requests.
 A Web form may contain directives, server-side scripts, client-side
scripts, static texts,Web controls, HTML controls, and many others.
Page Directives

 Page directives are used to set various attributes about a page.The ASP
Engine and the compiler follow these directives to prepare a page.
 There are many kinds of directives.The most frequently ones are the
following: @ Page, @ Import,@ Implements, @ Register,@ OutputCache
and @ Assembly directives.
 These directives can be placed anywhere in a page, however, these are
typically placed at the top.
Page Directives and Their Functions

a) @ Page
 We may use this directive to declare many page-related attributes
about a particular page. For example, we use this directive to declare
the language to be used in a page, such as
<%@ Page Language=”VB” Debug=”true” %>
 There are numerous attributes of this directive. Some of the
frequently used ones are these: AutoEventWireup, Buffer,
ClientTarget, EnableSessionState, ErrorPage, Debug, Trace,
TraceMode, and so on.
b) @ Import
 We use this directive to import a namespace in the page class file.
<%@ Import Namespace=”System.Data.OleDb” %>.
c) @ OutputCache
 We can use this directive to specify how to cache the page. In the
following example, we are setting the duration that a page or user
control is output cached:
<%@ OutputCache Duration=”10” /%>.
d) @ Register
 This directive is used to register a custom control in a page. In the
following example, we are registering one of our user custom controls
in page:
<%@ Register tagprefix =”utoledo” tagname=”Time”
Src=”TimeUserControl.ascx”%>.
e) @ Assembly
 We use this directive to link to an assembly to the current page or
user control. The following example shows how to link to an assembly-
named payroll:
<%@ Assembly Name=”Payroll” %>.
f) @ Implements
 This directive enables us to implement an interface in our page. In the
following example, we are implementing the IpostBackEventHandler
interface in one of our user controls:
<%@ Implements
Interface=”System.Web.UI .IPostBackEventHandler” %>.
Code-Behind versus In-Page Coding

 Placing a certain amount of VB code inside .aspx file is called In-Page


Coding/Inline code.
 All ASP applications had to be developed using in-page coding because
that was the only way to develop an ASP page.
 Intermixed HTML and scripting codes in a large page become cryptic
and difficult to read and maintain. Fortunately,ASP.NET provides a way
out of this problem.We may develop the html code in a file with an .aspx
extension, and then we may write the necessary code in a separate C# or
VB code file. This practice is known as Code-Behind.
 When we develop an ASP.NET application using VS.NET, we are
automatically forced to use Code-Behind.
 Obviously, the .aspx file has to be somehow linked to the class file.We
may link the .aspx file with the code file in one of two ways:
1) Develop the class file and save it without compilation in the same
directory of the .aspx file, or
a. You do not need to compile the VB or C# class/source file. Just save
the source file and the .aspx file in the same virtual directory.
b. You will need to enter the following Page Declarative statement at the
top of your .aspx file.
<%@ page language="VB" src="vbCb.vb"
inherits="myVbCodeBehind.vbCb" %>
2) Compile the class file and save the .dll file in the bin subdirectory of
our virtual directory.
Using HTML Server Controls

 Conventional HTML elements are not programmable at the server


side.Their values do not persist in postbacks.
 In ASP.NET, we may convert an HTML element to an HTML server
control by adding an attribute runat=“server.” This notifies the ASP
Engine to create an instance of the control during parsing. So, we will
need to specify an ID of the element so that we can manipulate it
programmatically at the server side.
 These controls are particularly useful for migrating ASP applications to
ASP.NET applications.
 HTML server controls must reside within a containing <form> control
with the runat=“server” attribute.
 The hierarchy of HTML server control classes are divided into three
major classes
1) HTML Input controls
HtmlInputButton, HtmlInputCheckBox, HtmlInputFile,
HtmlInputHidden, HtmlInputImage, HtmlInputRadioButton,
HtmlInputText
2) HTML Container controls
HtmlAnchor, HtmlButton, HtmlForm, HtmlSelect, HtmlTable,
HtmlTextArea, HtmlGenric Control
3) HTML Image control
HtmlImage
Using the HtmlAnchor Control

 You can use the HtmlAchor control (<a>) to navigate from a page to
another page.
<a runat = "server" id = "programmaticID" href ="linkurl" name =
"bookmarkname"
OnServerClick = "onserverclickhandler"
target="linkedcontentframeorwindow"
title="titledisplayedbybrowser">
 If necessary, we can use this control to dynamically modify the attributes
and properties of the <a> element and display hyperlinks from a data
source.
 The href attribute contains the URL of the page to be linked to.
Using the HtmlTable Control

 We may define rows using <tr> tags. Table cells are defined using <td>
tags.This control is a container control, and so we can embed other
controls in its cells.
 It has the following attributes:
<table runat="server" id="programmaticID" align=left|center|right
bgcolor="bgcolor"
border = "borderwidthinpixels" bordercolor="bordercolor"
cellpadding = "spacingwithincellsinpixels"
Cellspacing = "spacingbetweencellsinpixels" height="tableheight"
rows="collectionofrows" width="tablewidth" >
</table>
Using HtmlInputText and HtmlTextArea Controls

 You can use both of these controls to collect text data from the user.
 You can use the HtmlInputText control to implement server-side code
against the HTML <input type=text> and <input type=password> tags.
 Its major attributes are these: type (text or password), runat, id,
maxlength, size , and value.
 The HtmlTextArea control enables the user to enter multi-line text. It is
the server-side equivalent to the HTML <textarea> element. Its rows
and cols properties can be used to define its size. You can use its
onserverchange attribute to run an event handling function.
Using HtmlButton and HtmlImage Controls

 The HtmlInputButton supports the HTML Reset and Submit button types.
Using the HtmlInputFile Control

 The HtmlInputFile control has been designed to program against the


HTML <input type=file> element.
 We can use this control to enable users to upload binary or text files from
a browser to a directory that we specify in our Web server.
 Its major attributes are as follows:
<input type=file runat="server" id="programmaticID"
accept="MIMEencodings" maxlength="maxfilepathlength"
size="widthoffilepathtextbox" postedfile="uploadedfile" >
 To upload file from client machine to the server directory “C:\\temp” use
the following code:
fileControl.PostedFile.SaveAs((“c:\temp\” + targetName.Value))
 Page 124 -131
Using ASP.NET Web Controls

 Microsoft has included a plethora of Web controls in the


System.Web.UI.WebControls namespace.
 These controls can be divided into three major categories:
a) Basic Web Controls These Web controls are similar to HTML server
controls but have additional features. These controls have a richer
and more consistent object model.
b) Validation Controls These controls have been developed exclusively
for input validation.
c) Databound ListControls These belong to the new generation of
controls that provide additional power and development speed. These
are also typically referred to as Templated Web Controls.
 All Web controls are derived from the generic class named WebControl.
Basic Web Controls

 Label
 A Label is used to display text. If we want to display static text, we do
not need a Label server control; we should instead use HTML. We
should use a Label server control only if we need to change its
properties via server code.
 TextBox
 A TextBox control enables the user to enter text. By default, the
TextMode property is SingleLine, but it can also be set to Multiline or
Password. In case of Multiline text box, the Rows property determines
the height. If its AutoPostBack property is set to True, it generates a
PostBack on its Text_Changed() event.
 Button
 Button controls can be placed inside other container controls, such as
DataList, DataGrid and Repeater.
 LinkButton
 The LinkButton renders a hyperlink in the page.
 ImageButton
 The ImageButton displays an image that responds to mouse clicks. We
can also use it as an image map. Thus, we may pinpoint where in the
graphic the user has clicked.

 CheckBox
 It enables the user to input Boolean data: true or false, yes or no. Its
Checked property can also be bound to a data field of a data source. Its
CheckedChanged() event can be used for AutoPostBack.
 CheckBoxList / DropDownList / ListBox / RadioButtonList
 These controls are derived from the ListControl abstract class.
 All three types of buttons (Button, LinkButton and Image button) cause
PostBacks when the user clicks them.
 HyperLink
 It displays a link to another page. It is typically displayed as text
specified in its Text property. It can also be displayed as an image
specified in the ImageUrl property. If both the Text and ImageUrl
properties are set, the ImageUrl property is displayed. If the image
does not exist, then the text in the Text property is shown. Internet
Explorer uses the Text property to display ToolTip.
 Image
 We may use the Image control to display an image on the Web page.
The ImageUrl property specifies the path to the displayed image.
When the image does not exist, we can specify the text to display in
place of the image by setting the AlternateText property. The Image
control only displays an image. If we need to capture mouse clicks on
the image, we should instead use the ImageButton control.
 Panel
 This can be used as a container of other controls. This control is
rendered as an HTML <div> element.
 RadioButton
 It creates an individual radio button on the page. We can group them
to present mutually exclusive choices.
 Table
 It enables us an HTML table. A table can be built at design time with
static content, but the Table control is often built programmatically
with dynamic contents. Programmatic additions or modifications to a
table row or cell do not persist on PostBack. Changes to table rows or
cells must be reconstructed after each post to the server. In these
cases, better alternatives are DataList or DataGrid controls.
 Xml
 This control can be used to transform XML documents.
Using the ListControl Abstract Class

 A number of basic Web controls have been derived from the ListControl
abstract class.These are CheckBoxList, DropDownList, ListBox, and
RadioButtonList.
 We can set their AutoPostBack properties to true to trigger postbacks on
their SelectedIndexChanged events.
 The Items(i).Selected property can be used to check if the user has
selected an item in the list and the Items(i).Text property enables us to
extract the text of the selected item.
Using HyperLink Controls

 The HyperLink server control enables us to link to a different page.


 Its Text property is displayed on the screen as a hyperlink. On click of
the hyperlink, it linksto a page specified in its NavigateUrl property. The
displayed text can be replaced by an image by specifying the ImageUrl
property.
Validation Controls

 A validation control enables us to validate an input and display an error


message if necessary.
 First, the server treats it as an invisible control. After the user has
entered erroneous data, it becomes visible.
 Various types of validation controls are as follows:
 RequiredFieldValidator - Checks if the input control has any value.
 RegularExpressionValidator - Checks the value against a regular
expression (pattern).
 CompareValidator - Checks if the value is acceptable compared to a
given value or compared to the content of another control.
 RangeValidator - Checks if the input control’s value is within a
specified range.
 CustomValidator - Allows you to develop custom validation.
 ValidationSummary - Reports a summary of all errors.
 By default, each of the validation controls performs the validation task at
the client-side as well as at the server-side.
 Except for the RequiredFieldValidator, all other validation controls treat
an empty field as a valid field.Therefore, we will need to apply a
RequiredFieldValidator to every input field that we want to validate.
 You can attach more than one validation control to an input. For
example, we may use a RequiredFieldValidator and a RangeValidator to
ensure that an input is not empty and falls within a specified range.
 There are a number of common properties in these controls.The major
ones are:
 ErrorMessage - In case of an error, the system displays this message
at the location of the control, and in the summary report, if any.
 Display - A validation control is kept invisible until a bad input is
entered. In case of a bad input, the system has to display the error
message. The display mechanism can be handled in one of three ways.
a) Display= “static” Initially, enough room in the page is reserved
for the expected error message.
b) Display= “dynamic” No room is initially reserved. In case of an
error, the message is displayed by displacing existing contents of
the page.
c) Display=“none” The message won’t be displayed at the location of
the control; however, it will be reported in the summary report, if
any.
The RequiredFieldValidator Control

 In the following example, the user is expected to enter two values. If he


or she skips any one of the values and clicks the Submit button, the
system will report the error.
<asp:TextBox id="txtName" rows="1 " width="50" runat="server"/>
<asp:RequiredFieldValidator id="validTxtName" runat="server"
controlToValidate="txtName" errorMessage="Name must be
entered" display="static">
</asp:RequiredFieldValidator>
The RegularExpressionValidator Control

 The RegularExpressionValidator control is typically used to match an


input pattern.
 If we have a textbox named txtH that can only take one to three digit,
you can specify the validation as follows:
<asp:TextBox id="txtH" rows="1 " width="50" runat="server"/>
<asp:RegularExpressionValidator id="regvH" runat="server"
display="static" controlToValidate="txtH"
errorMessage="Hours must be 1-3 digits only"
validationExpression="\d{1,3}">
</asp:RegularExpressionValidator>
Note
 You can get more regular expression from
www.microsoft.com/mind/defaulttop.asp?page=/mind/1098/jscript/
jscript.htm&nav=/mind/1098/inthisissuecolumns1098.htm.

The CompareValidator Control

 The CompareValidator control compares an input to a specified value or


to the value of another control.You can also use it to check if the input is
of any particular data type.
 If we have a textbox named txtR and in this textbox, the user is suppose
to enter a value its data-type to be Double. We will apply a
CompareValidator control to test the data-type of the txtR. Note that if
the data entered is convertible to the desired data-type, the validation
will succeed. See the following code:
<asp:TextBox id="txtH" rows="1 " width="50" runat="server"/>
<asp:CompareValidator id="comvR" runat="server" display="static"
controlToValidate="txtR" errorMessage="Rate must be
numeric" type="Double" operator="DataTypeCheck">
</asp:CompareValidator>
 Please notice that the above code have set the type property to “Double,”
and the operator property to “DataTypeCheck.”
 In the type property of the CompareValidator, we may specify: String,
Integer, Double, DateTime, and Currency. In the operator property, we
may specify: Equal, NotEqual, GreaterThan, LessThan,
GreaterThanEqual, LessThanEqual, and DataTypeCheck.
The RangeValidator Control

 You can use this control to check if an input is within an acceptable


range.
 Suppose that you want to provide a textbox for collecting data and you
want to enforce a constraint that this field should take from 0 to 10. See
the following code:
<asp:TextBox id=" txtDependents " rows="1 " width="50"
runat="server"/>
<asp:RangeValidator id="ranvDependents" runat="server"
display="static" controlToValidate="txtDependents"
errorMessage="Must be from 0 to 10" type="Integer"
minimumValue=0 maximumValue=10>
</asp:RangeValidator>
The CustomValidator Control (page 149 – 152 to be coved)
The ValidationSummary Control

 The ValidationSummary control enables us to display all errors in a given


location.
 It displays the “errorMessage” properties of respective controls in the
summary report.
 Major properties of the ValidationSummary control are the following:
 HeaderText - This is simply a header.
 DisplayMode - Displays the errors in one of the following ways:
a) List
b) BulletList (default)
c) Singleparagraph
 ShowSummary: (True or False) - This property can be used to display
or hide the summary report programmatically.
<asp:ValidationSummary id="valSummary" runat="server"
headerText="Please correct the following errors"
display="static" showSummary= "True" />
Validating Patterned Strings, Passwords, and Dates

 Suppose that we want the user to enter the phone number, date of birth,
hiredate, password, and confirmation of password in a specified format
therefore you can put constraint as follows:
 The phone number must follow a pattern like (ddd)ddd-dddd for
employees in the USA. It should match dd.dd.dd.dd for employees in
France.
 The date of birth must be between 1/1/1940 and 1/12/1985.
 Hire date must be after the date of birth and before 6/15/2001.
 The user should enter the password twice, and both entries must be
identical.
<asp:RangeValidator id="ranvDateHired" runat="server"
type="Date" display="dynamic"
controlToValidate="txtDateHired" errorMessage="Hire date
must be before 6/1/2001" minimumValue="1/1/1900"
maximumValue="6/15/2001" >
</asp:RangeValidator>

<asp:CompareValidator id="comvConfirmPassword" runat="server"


display="static" controlToValidate="txtConfirmPassword"
controlToCompare="txtPassword" errorMessage="Both
passwords must be same" type="String" operator="Equal">
</asp:CompareValidator>
The Databound ListControls Family

 Populating myDataSet and Binding a ListControl


Sub bindListControl()
Dim myConn As OleDbConnection
Dim myOleDbAdapter As OleDbDataAdapter
Dim connStr, sqlStr As String
Dim myDataSet As New Dataset
connStr="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\
Products.mdb"
sqlStr="SELECT ProductId, ProductName, Price, ImagePath "
+ "FROM Products WHERE Price>45.00 ORDER BY Price"
myConn= New OleDbConnection(connStr)
myConn.Open()
myOleDbAdapter =New OleDbDataAdapter(sqlStr,myConn)
myOleDbAdapter.Fill(myDataSet,"dtProducts")
repeater1.DataSource=myDataSet.Tables("dtProducts")
repeater1.DataBind()
End Sub
Using the Repeater Server Control

 The Repeater is essentially a template-driven data-bound list.The


Repeater control allows fragments of html tags inside the templates.
 The control binds its Item collection to the its DataSource.We may use
the Item Command event to process events that are raised from the
templates of the control.
 We may specify the following templates for a Repeater control:
 Item Template Specifies the DataItem fields to be displayed, and the
layout (required).
 AlternatingItemTemplate Defines the layout of the zero-based odd
indexed items (optional).
 SeparatorTemplate In this template, we can specify the separator
such as <hr> or <br> between repeating items (optional).
 HeaderTemplate Specifies the header of the list (optional).
 FooterTemplate Specifies the footer of the list (optional).
Displaying Data in a Repeater Control

<body><h2><center>Cathy's E-Shop</h2>
<asp:Repeater id="repeater1" runat="server" >
<HeaderTemplate><table></HeaderTemplate>
<ItemTemplate><tr>
<td><asp:Image height=100 width=100 Img src='<%#
Container.DataItem("ImagePath")%>'
runat="server"/>
</td>
<td>Product ID:
<%# Container.DataItem("ProductId")%><br>
Description: <b><i>
<%# Container.DataItem("ProductName")%></b><i><br>
<b>Unit Price:
<%#
FormatCurrency(Container.DataItem("Price"))%></b><br>
</td></tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</center>
</body>
Using Event Bubbling and Capturing Events in a Repeater Control

(Page 166 – page 169)

Using the DataList Control

(Page 170 – page 175)


Using the DataGrid Control
 The DataGrid Control happens to be the most versatile and powerful
member of the data-bound control family.
Displaying Data in a DataGrid Control Using Default Column
Mapping
 In the example below, we will use the default layout of a data grid to
display the bound data. The DataGrid control also requires binding to an
appropriate data source.

<!— Chapter3/DataGrid2.aspx —>


<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html><head></head>
<script language="VB" Debug="true" runat="server">
Sub Page_Load(Source As Object, E As EventArgs)
If Not IsPostBack Then
bindListControl
End If
End Sub
Sub sortGrid(s As Object, e As DataGridSortCommandEventArgs)
bindDataGrid(e.sortExpression)
End Sub
Sub bindListControl(Optional sortField As String="ProductId")
Dim myConn As OleDbConnection
Dim myOleDbAdapter As OleDbDataAdapter
Dim myDataSet As New DataSet
Dim connStr, sqlStr As String
connStr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\
Products.mdb"
sqlStr="SELECT ProductId, ProductName, Price " _
+ " FROM Products WHERE Price > 40 ORDER BY " + sortField
myConn= New OleDbConnection(connStr)
myConn.Open()
myOleDbAdapter =New OleDbDataAdapter(sqlStr,myConn)
myOleDbAdapter.Fill(myDataSet,"dtProducts")
DataGrid1.DataSource=myDataSet.Tables("dtProducts")
DataGrid1.DataBind()
myConn.Close()
End Sub
</script>

<asp:DataGrid runat="server" id="DataGrid1"


AutoGenerateColumns="false" Width="75%" BackColor="White"
BorderWidth="1px" BorderStyle="Solid" CellPadding="2"
CellSpacing="0" BorderColor="Salmon" Font-Name="Verdana" Font-
Size="8pt" AllowSorting="true" OnSortCommand ="sortGrid">
<HeaderStyle Font-Size="8" Font-Names="Arial" Font-Bold="True"
BackColor="Yellow" HorizontalAlign="center">
</HeaderStyle>
<Columns>
<asp:BoundColumn HeaderText="Product ID" DataField="ProductId"
>
<ItemStyle HorizontalAlign="Right"/>
</asp:BoundColumn>
<asp:BoundColumn HeaderText="Unit Price" DataField="price"
DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="Right"/>
</asp:BoundColumn>
<asp:BoundColumn HeaderText="Description"
DataField="ProductName">
<ItemStyle Width="130"/>
</asp:BoundColumn>
</Columns>
<AlternatingItemStyle BackColor="Beige"/>
</asp:DataGrid>
</center></body></html>

You might also like