Title: ASP'NET Server Controls
1ASP.NET Server Controls
- David Turton
- Conestoga College
- Institute of Technology and Advanced Learning
- http//www.conestogac.on.ca/dturton
- Doon 1D17 x3610
2Objectives
- Create web pages using HTML and ASP.NET controls
- Examine their differences
- Create and process a form using
- HTML Server controls
- ASP.NET controls
- Populate controls dynamically using ArrayLists
and HashTables - Validate a form using Validation controls
3Transporting Your Site
- Solution is on G (not available at home)
- Can change default location
- Tools ? Options ? Projects Solutions
- But .aspx pages code are in project folder
- Create/copy folder onto USB device
- Suggestion File?Open?Web Site
- Select folder with your .aspx and code
- Will create a solution
- On "Save", put this into the project folder
- Later
- Double-click .sln file to open web site
4Can Still Use HTML
- Most layout controls are just HTML
- ltpgt, ltbr/gt, lttablegt, ltligt, ltdivgt, etc.
- Form controls have ASP.NET alternatives
- Can convert HTML to HTML Server Controls
- Add attributes runat"server" id"someId"
- Become accessible to code
- Can read or modify values (properties)
- But must handle their events using javascript
- Not VB or C events in code
- New "feature" in VS2008
- Ms doesn't like HTML server controls
5Property Items CollectionRadioButtonList,
CheckBoxList, DropDownList, ListBox
- The Items collection has two parts
- The Text the user sees selects
- New Brunswick"
- The Value of the user's selection
- NB"
- If you load just the text part
- The values will be identical
6single Radio ButtonsASP.NET controls
- RadioButton
- .Id property
- Buttons individually identified
- If rbFedEx.Checked Then ...
- .Text property
- Label beside radio button
- .GroupName property
- Mutually-exclusive group identifier
7RadioButtonList ASP.NET controls
- RadioButtonList
- .Id property
- One for whole list
- Identify selection by its value
- If rbPayment.SelectedValueMC" Then ...
- .SelectedIndex property
- -1 means "nothing selected"
- Don't use to identify selection
- Item collection
- List of static Text/Value pairs
- Not used much in ASP.NET
8Populating a RadioButtonList
- Static, in HTML template (dont use)
- Items property (a collection)
- Dynamic, in code
- rbControl.Items.Add("Visa")
- or
- rbControl.DataSourcevariable
- Connected to a collection (Hashtable, Arraylist)
- Connected to a database table
- May need to identify DataTextField
DataValueField (later) - Follow with rbControl.DataBind()
- To bind (upload) values from code to controls
Items
9CheckBox CheckBoxList
- Loaded same way as radio buttons
- However, can have multiple selections
- .SelectedValue ... just 1st selection
- .SelectedIndex-1 if nothing selected
- Loop to find all selections
For i As int32 To chkSymptom.Items.Count 1
If chkSymptom.Items(i).Selected Then
choices chkSymptom.Items(i).Value "ltbr /gt"
End If Next
or .Text
10DropDownList ListBoxASP.NET controls
- Resolve to HTML ltselectgt ltoptiongt elements
- DropDownList
- Single-entry selection
- ListBox
- Single- or multiple-entry selection
- Loading values
- Like RadioButtonList
- Static via Items collection
- Dynamic via DataSource property
11Processing a Drop-Down Listonly 1 item can be
selected default 1st entry
- You usually load it in Page_Load event handler
- Watch IsPostback, a Boolean system variable
- False initial load of page to browser load
drop-down - True page is being returned from browser
- User has made selections don't reload lists over
them - To use the selected value
- if ddProvince.SelectedValue "BC" Then
- Checks value of a selected item
- Can also check .SelectedItem.Value
.SelectedItem.Text - ddProvince.SelectedIndex
- -1 ? nothing selected
- Don't use for anything else ...
- Lists change hard-coded indexes usually don't
keep up
12Processing a ListBoxSelectionMode"Multiple" or
"Single"
- xxx.SelectedValue
- Just the first selected value
- xxx.SelectedIndex-1
- If true, nothing was selected
- .SelectionMode"Multiple"
- Loop to look at each entry
- .Items.Count starts at 1
- .Items indexed from 0
For i As Int32 0 To lstHear.Items.Count -1
If lstHear.Items(i).Selected Then
choices lstHear.Items(i).Value "ltbr /gt"
End If Next
13AutoPostBack
- Property on DropDownList ListBox
- Raises SelectedIndexChanged event
- Event handler can modify form contents
- Like a button
- AutoPostBack
- Default false
- Usually just data entry
- Change to react to user input
14Binding Controls to ArrayLists HashTables
- To bind an object to a list is
- To populate the object's .Items array
- List can be an ArrayList, HashTable or database
- ArrayList
- 1-dimensional array
- Dynamically created extended
- HashTable
- 2-dimensional array
- Key/Value pairs
- Dynamically created extended
15Bind Process
- In HTML template
- Add a control
- RadioButtonList, CheckBoxList, DropDown, DataList
- In code
- Declare build an ArrayList or HashTable
- Dim myArray as New ArraryList()
- myArray.Add(xxxxx)
- Declare list as controls DataSource property
- If using HashTables
- Set tables Value or Key as the controls
dataValueField and DataTextField properties - Bind control using DataBind() whole page or
control - If modify list, have to re-bind control
- Note list/table not retained after page sent to
browser
16Binding a DropDown to a HashTable
- Hash table is a collection of Key ? Value pairs
- Need to tell control which field to show the
user - and which to return as control's selected value
17Binding a RadioButtonList to an ArrayList
- ArrayList is a 1-dimensional collection
- Control will recognise this
- will make value and text parts the same.
- Easy way to make 2, 3 or 12 radio buttons
- whatever the data requires
18Vertical (Table Flow)
Playing with CheckBoxList properties
RepeatDirection and RepeatLayout
Horizontal Flow
Horizontal Table
Note entries are not ordered the same as the
table alphabetically or by length
19Creating a Hyperlink HTML Server Control
Convert to hyperlink
- Select phrase or icon to be hyperlink
- Format ? Convert to hyperlink
- Type
- http web page
- mailto email
- URL
- Absolute link
- (other)
- Usually relative link
- ltAgt link created
- Convert to server control
- Can access Href in code
Use relative references for pages on your site,
so they still work when uploaded to server
20Creating a Hyperlink ASP.NET control
Use relative references to internal hyperlinks,
so they still work when you upload to a server
21Hyperlinks
- Never use //localhost references
- Never use Windows drive letters
- On upload to a server, these will fail.
- Use relative references for your site
- Besides, you lose marks
22PanelASP.NET Controls
- Like HTMLs ltfieldsetgt
- GroupingText is caption for panel
- Height width properties reserve space
- Can contain other controls text
- Added during design process
- If make panel invisible
- All controls on it become invisible
- Better than hiding them individually
23PlaceholderContainer for dynamically added
controlsOccupies no space if empty
- Create a new control object and add it to the
placeholder. - You can modify the control's properties
- You must give the control an ID
- The variable myLabel only exists for this session
- Refer to control's ID if accessing it later
- Other objects
- Literal() ? straight text, no ltspangt like
Label() - Hyperlink() ? use Text/ImageURL navigateURL for
target
24ASP.NET Validation Controls
25Validation Controls
- Will create client-side JavaScript checks
- If client permits
- Otherwise, runs server-side checks
- Validation errors will inhibit postback
- Stops submission of the form
- Even if error checks are server-side
- Validations act like onChange events
- Page.Validate() method
- Run all validation controls on a page
- Page.IsValid property
- (True/False) indicates if any check failed
- Used in code to force server-side check.
26Validation Controls
- Same properties as Label class, plus
- ControlToValidate
- Which control is this validating (which TextBox,
etc.)? - Display
- Reserve space for validation message?
- "dynamic" space added dynamically if fails
validation - "static" space allocated on page, pass or fail
- "none" never displayed (use validation summary
control) - Text
- Text displayed if control is invalid
- ErrorMessage
- Message on validation summary if control is
invalid - Default error message if Text not specified
- IsValid
- True/False
- and several others
27Note on .Text vs .ErrorMessage
- .ErrorMessage by itself is common
- What if you're using a summary block or pop-up
- and you want to highlight fields in error?
- Use .Text
- For an error-flag
- like "" beside field in error
- Use .ErrorMessage
- For longer error message in pop-up
28Validation ControlsRange, Required-Entry
- RequiredFieldValidator
- See if any value has been entered or selected
- Note
- other validators don't check for empty/null
controls - ControlToValidate
- identifies control being checked
- RangeValidator
- See if value is within a specified range
- ControlToValidate
- identifies the control being checked
- MinimumValue and MaximumValue
- is the range (inclusive)
- Type
- Is the type of data comparison
- "String", "Integer", "Double", "Date", "Currency"
29Validation Controlscompare
- CompareValidator
- Compares one control's value to another's, a
constant or a data type - ControlToValidate
- identifies control that'll get the error
- ControlToCompare
- identifies a control to compare to
- Ignored for a DataTypeCheck
- ValueToCompare
- (alternate) a constant to compare to
- Operator
- specifies the type of comparison
- Equal means the fields must be equal to be valid
- DataTypeCheck only checks control's contents to
the specified type - Type
- Is the type of data comparison
- "String", "Integer", "Double", "Date", "Currency"
30Hacking Web Sites
- If youre expecting a number
- Check for it with a compare validator
- Inhibit post-back if something else is entered
- Why?
- Instead of 28 for a part ID, type
- 28 UPDATE part SET price17
- If input blindly appended to SELECT statement
- SELECT FROM part WHERE partId28 UPDATE part
SET price17 - ends the SELECT
- UPDATE becomes 2nd SQL command to database
- All parts (no WHERE clause on update) are now
17.00
31Validation ControlsRegular Expression
Validation Summary
- RegularExpressionValidator
- Matches a control's value to a regular expression
pattern - (\(\d3\) )?\d3-\d4
- ControlToValidate
- identifies the control
- ValidationExpression
- is the regular expression
- VS.NET has several canned regular expressions
- but someone forgot to load the Canadian ones
- ValidationSummary control
- Summarises error messages from all controls
- Usually, inhibit other validation controls from
displaying individually - Set other controls display property to none or
use Text property - DisplayMode
- BulletList, List or SingleParagraph
- ShowMessageBox
- uses a pop-up
Hmmm and are assumed
32Drag Validation rule to location for message
33ErrorMessage displayed on Validation
SummaryText displayed beside control when it's
in error note if Text blank, ErrorMessage is
used in both places
34Indicate ControlToValidate required conditions
35Send-To-Server Regardless
- Validation errors stop postback
- But user may need to cancel a page
- To have a button ignore validation errors
- Turn off CausesValidation