Home arrow News - Articles arrow Teaching things arrow ASP.NET Week 3 : Validator, Table,File
 
  XnRnXZvLpO www.danielhp.com
ASP.NET Week 3 : Validator, Table,File PDF Print E-mail
Written by Administrator   
Tuesday, 09 June 2009
Materi Minggu ke 3. Dibagi menjadi 2 bagian. Bagian pertama tentang Webform control untuk validasi input. Tidak pakai latihan. Bagian kedua tentang webform control Table. Bagaimana caranya membuat table saat runtime. Dialnjutkan dengan membaca textfile. Dan diakhiri dengan latihan yg menggabungkan Table dengan textfile.

No

Materi

Sub Materi

t

note

Link

1

Validation Control

Required Field Validator

10

Contohkan untuk username tidak boleh kosong. Satu input bisa dicek dengan banyak vlidator

Validation control

 

 

Compare Validator

10

Contohnya password dan konfirmasi-nya

 

 

 

Range Validator

10

Contohnya tahun kelahiran

 

 

 

RegularExpression Validator

10

Contohnya untuk alamat email, url website, dll

 

 

 

CustomValidator

10

Contohkan yg simpel yang penting tahu cara membuatnya. Misal bikin input yg dicek apakah angkanya ganjil.

  • Buat sub pengecekan
  • Panggil sub tadi di onServerValidate

 

 

 

Validation Summary

10

Misal error2 di groupkan di satu tempat, tidak di tiap-tiap input

 

 

 

 

 

 

 

2

WebForm Table

Membuat table secara runtime

30

Buat table, isikan text. Coba isikan juga tombol. Diganti2 tampilannya misal backcolor

table

3

File Text

Membaca File Text

30

Dengan streamreader

Read file

4

Latihan

 

30

Menggabungkan antara pembuatan table secara runtime dengan data diambil dari textfile

latihan

 

Validating User Input in ASP.NET Web Pages 

You can add input validation to ASP.NET Web pages using validation controls. Validation controls provide an easy-to-use mechanism for all common types of standard validation—for example, testing for valid dates or values within a range—plus ways to provide custom-written validation. In addition, validation controls allow you to customize how error information is displayed to the user.

Using Validation Controls

You enable validation of user input by adding validation controls to your page as you would add other server controls. There are controls for different types of validation, such as range checking or pattern matching. For a complete list of validation types, see Types of Validation for ASP.NET Server Controls. Each validation control references an input control (a server control) elsewhere on the page. When user input is being processed (for example, when a page is submitted), the validation control tests the user input and sets a property to indicate whether the entry passed the test. After all of the validation controls have been called, a property on the page is set indicating whether any validation check has failed.
Validation controls can be associated into validation groups so that validation controls belonging to a common group are validated together. You can use validation groups to selectively enable or disable validation for related controls on a page. Other validation operations, such as displaying a ValidationSummary control or calling the GetValidators method, can reference the validation group.
You can test the state of the page and of individual controls in your own code. For example, you would test the state of the validation controls before updating a data record with information entered by the user. If you detect an invalid state, you bypass the update. Typically, if any validation checks fail, you skip all of your own processing and return the page to the user. Validation controls that detect errors then produce an error message that appears on the page. You can display all validation errors in one place using a ValidationSummary control.

information, see Script Exploits Overview.

Type of validation

Control to use

Description

Required entry

RequiredFieldValidator

Ensures that the user does not skip an entry. For details, see How to: Validate Required Entries for ASP.NET Server Controls.

Comparison to a value

CompareValidator

Compares a user's entry against a constant value, against the value of another control (using a comparison operator such as less than, equal, or greater than), or for a specific data type. For details, see How to: Validate Against a Specific Value for ASP.NET Server Controls and How to: Validate Against a Data Type for ASP.NET Server Controls.

Range checking

RangeValidator

Checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates. For details, see How to: Validate Against a Range of Values for ASP.NET Server Controls.

Pattern matching

RegularExpressionValidator

Checks that the entry matches a pattern defined by a regular expression. This type of validation enables you to check for predictable sequences of characters, such as those in e-mail addresses, telephone numbers, postal codes, and so on. For details, see How to: Validate Against Patterns for ASP.NET Server Controls.

User-defined

CustomValidator

Checks the user's entry using validation logic that you write yourself. This type of validation enables you to check for values derived at run time. For details, see How to: Validate with a Custom Function for ASP.NET Server Controls and How to: Validate Against Values in a Database for ASP.NET Server Controls.

You can attach more than one validation control to an input control. For example, you might specify that a control is required and that it also contains a specific range of values.
A related control, the ValidationSummary control, does not perform validation, but is often used in conjunction with other validation controls to display the error messages from all the validation controls on the page together. For more information, see How to: Control Validation Error Message Display for ASP.NET Server Controls.

 When Validation Occurs

Validation controls perform input checking in server code. When the user submits a page to the server, the validation controls are invoked to check the user input, control by control. If a validation error is detected in any of the input controls, the page itself is set to an invalid state so you can test for validity before your code runs. Validation occurs after page initialization (that is, after view state and postback data have been processed) but before any change or click event handlers are called.
If the user is working with a browser that supports ECMAScript (Javascript), the validation controls can also perform validation using client script. This can improve response time in the page because errors are detected immediately and error messages are displayed as soon as the user leaves the control containing the error. If client-side validation is available, you have greater control over the layout of error messages and can display an error summary in a message box. For more information, see Client-Side Validation for ASP.NET Server Controls.
ASP.NET performs validation on the server even if the validation controls have already performed it on the client, so that you can test for validity within your server-based event handlers. In addition, re-testing on the server helps prevent users from being able to bypass validation by disabling or changing the client script check.
You can invoke validation in your own code by calling a validation control's Validate method. For more information, see How to: Validate Programmatically for ASP.NET Server Controls.
 Validating for Multiple Conditions
Each validation control typically performs one test. However, you might want to check for multiple conditions. For example, you might want to specify both that a user entry is required and that the user entry is limited to accepting dates within a specific range.
You can attach more than one validation control to an input control on a page. In that case, the tests performed by the controls are resolved using a logical AND operator, which means that the data entered by the user must pass all of the tests in order to be considered valid.
In some instances, entries in several different formats might be valid. For example, if you are prompting for a phone number, you might allow users to enter a local number, a long-distance number, or an international number. Using multiple validation controls would not work in this instance because the user input must pass all tests to be valid. To perform this type of test—a logical OR operation where only one test must pass—use the RegularExpressionValidator validation control and specify multiple valid patterns within the control. Alternatively, you can use the CustomValidator validation control and write your own validation code.
 Displaying Error Information
Validation controls are not normally visible in the rendered page. However, if the control detects an error, it displays the error message text that you specify. The error message can be displayed in a variety of ways, as listed in the following table.


Display method

Description

Inline

Each validation control can individually display an error message in place (usually next to the control where the error occurred).

Summary

Validation errors can be collected and displayed in one place—for example, at the top of the page. This strategy is often used in combination with displaying a message next to the input fields with errors. If the user is working in Internet Explorer 4.0 or later, the summary can be displayed in a message box.
If you are using validation groups, you need a ValidationSummary control for each separate group.

In place and summary

The error message can be different in the summary and in place. You can use this option to show a shorter error message in place with more detail in the summary.

Custom

You can customize the error message display by capturing the error information and designing your own output.

If you use the in-place or summary display options, you can format the error message text using HTML.


Security noteSecurity Note

If you create custom error messages, make sure that you do not display information that might help a malicious user compromise your application. For more information, see How to: Display Safe Error Messages.

 Validation Object Model
You can interact with validation controls by using the object model that is exposed by individual validation controls and by the page. Each validation control exposes its own IsValid property that you can test to determine whether a validation test has passed or failed for that control. The page also exposes an IsValid property that summarizes the IsValid state of all the validation controls on the page. This property allows you to perform a single test to determine whether you can proceed with your own processing.
The page also exposes a Validators collection containing a list of all the validation controls on the page. You can loop through this collection to examine the state of individual validation controls.


NoteNote

There are a few differences in the object model for client-side validation. For more information, see Client-Side Validation for ASP.NET Server Controls.

 Customizing Validation
You can customize the validation process in the following ways:

  • You can specify the format, text, and location of error messages. In addition, you can specify whether the error messages appear individually or as a summary.
  • You can create custom validation using CustomValidator control. The control calls your logic but otherwise functions like other validation controls in setting error state, displaying error messages, and so on. This provides an easy way to create custom validation logic while still using in the validation framework of the page.
  • For client-side validation, you can intercept the validation call and substitute or add your own validation logic.

Table Web Server Control Overview 

The Table Web server control allows you to create server-programmable tables on ASP.NET pages. The TableRow and TableCell Web server controls provide a way to display the actual content for the Table control.
 Comparing the Table Web Server Control to Other Table Elements
Tables are typically used not only to present tabular information, but as a way to format information on a Web page. There are a number of ways to create tables on your Web Forms page:

  • HTML table. You can add an HTML <table> element. If you are creating a static table (one in which you will not add or change content at run time), you should use an HTML table and not a Table control.
  • HtmlTable control. This is a <table> HTML element that has been converted to an HTML server control by adding the runat=server attribute. You can program this control in server code. For details about HTML server controls, see ASP.NET Web Server Controls Overview.
  • Table. A Web control that allows you to create and manipulate tables (for example, adding table rows and cells) using an object model that is consistent with other Web controls.

In general, you use a Table Web server control when you intend to add rows and cells (columns) to the table in code at run time. Although you can use it as a static table with predefined rows and columns, it is easier in this case to work with the HTML <table> element.
The Table Web server control can be easier to program than the HtmlTable control because it offers an object model with typed properties that is consistent with other Web server controls. (The model is also consistent between the Table, TableRow, and TableCell controls.)
 Comparing the Table Web Server Control to Other List Web Server Controls
Some of the functions you might accomplish with a Table Web server control can also be accomplished with the list Web server controls, specifically the Repeater, DataList, and GridView controls. All these controls are rendered (or have the option to be rendered) as HTML tables.
The differences between the list controls and the Table control are these:

  • The list controls are data-bound. The list controls work only against a data source, whereas the Table control can display any combination of HTML text and controls, whether or not they are data-bound.
  • The list controls use templates to specify the layout of their elements. The Table control supports the TableCell child control, which you can fill as you would any HTML <td> element.

 Table Web Server Control Object Model
The Table control acts as a parent control for TableRow controls. The table supports a property called Rows that is a collection of TableRow objects. By managing this collection — adding or deleting items in it — you specify the rows for the table. The TableRow control in turn supports a collection called Cells that contains TableCell objects.
The content to be displayed in the table is added to the TableCell control. The cell has a Text property that you set to any HTML text. Alternatively, you can display controls in the cell by creating instances of, and adding controls to, the cell's Controls collection.
The parent Table control supports properties to control the appearance of the entire table, such as Font, BackColor, and ForeColor. The TableRow and TableCell controls support these properties as well, so you can specify the look of individual rows or cells, overriding the parent table appearance.

Example Creating Table in Runtime

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim i, j As Long
        For i = 1 To 4
            Dim tRow As New TableRow
            For j = 1 To 5
                Dim tCell As New TableCell
                tCell.Text = "Row " & i & ", Cell " & j
                Dim bt As New WebControls.Button
                bt.Text = "Row " & i & ", Cell " & j
                'tCell.Controls.Add(bt)
                tCell.BackColor = Color.FromArgb(RGB(i * 20, j * 40, (i + j) * 10))
                ' Add new TableCell object to row.
                tRow.Cells.Add(tCell)
            Next
            ' Add new row to table.
            Table1.Rows.Add(tRow)
        Next

    End Sub

 

 

 

Read Text File

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim f As IO.File
        Dim FILENAME As String = Server.MapPath("f.txt")

        'Get a StreamReader class that can be used to read the file
        Dim os As IO.StreamReader
        os = New IO.StreamReader(FILENAME)
        While os.Peek() >= 0
            Response.Write(os.ReadLine() & "<br>")

        End While

        os.Close()

    End Sub

                                         

 

Latihan

Terdapat text file dengan susunan seperti berikut :

tukul
jakarta
avatar1.jpg
ronaldo
manchester
avatar2.jpg
messi
barcelona
avatar3.jpg

Buatlah agar dibaca dan menapilkan bentuk table seperti berikut :

 

 

JAWABAN

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Table1.BorderStyle = BorderStyle.Double
        Table1.BorderColor = Color.Black

        Dim tr As TableRow
        tr = New TableRow
        Dim tc As TableCell
        tc = New TableCell
        tc.Text = "Nama"
        tr.Cells.Add(tc)
        tc = New TableCell
        tc.Text = "Alamat"
        tr.Cells.Add(tc)
        tc = New TableCell
        tc.Text = "Foto"
        tr.Cells.Add(tc)
        tr.BackColor = Color.Cyan

 

        Table1.Rows.Add(tr)
        Dim i As Long
        Dim filename As String = Server.MapPath("tes2.txt")
        Dim sr As IO.StreamReader = New IO.StreamReader(filename)
        While sr.Peek >= 0
            tr = New TableRow
            tc = New TableCell
            tc.Text = sr.ReadLine
            tr.Cells.Add(tc)
            tc = New TableCell
            tc.Text = sr.ReadLine
            tr.Cells.Add(tc)
            tc = New TableCell
            Dim im As New WebControls.Image
            im.ImageUrl = sr.ReadLine
            tc.Controls.Add(im)
            tr.Cells.Add(tc)

            tr.BorderStyle = BorderStyle.Inset
            Table1.Rows.Add(tr)
        End While
    End Sub

 

Comments
Search
Chestnut Dakota Ugg Casuals
Chestnut Dakota Ugg Casuals (58.22.77.xxx) 2009-08-10 02:21:38

There I was, my first day On the Job as a receptionist,Espresso Brown Morocco Ugg Sandals handling one phone call after another like an old pro, when an employee
stopped by my desk.Sand Champagne Morocco Ugg Sandals "Have you ever done this before?" she asked. "No," I said.
"Thought not. You just told that caller.
sajiannn (222.212.43.xxx) 2009-08-20 08:12:11

Reporting from Kabul, wow goldAfghanistan - Insurgents struck atwow goldwow gold the main symbol of the wow goldWestern military presence wow goldin Afghanistan today, killing atwow goldwow gold least seven peoplewow gold and injuring nearly wow gold100 others in a massivewow gold car bombing wow goldfive days beforewow goldnationwide elections.
sajiannn (222.212.43.xxx) 2009-08-20 08:19:43

BIG SKY, Montana dofus kamaskamas dofus(Reuters) - President acheter dofusBarack Obama acheter kamassaid on Saturday U.S.dofus kamaskamas dofus healthcare worked dofus kamasbetter for insurance companieskamas dofus than for patients, acheter kamasas he presseddofus kamaskamas dofus his case for a majorachat kamas overhaul that dofus kamaskamas dofuscritics say is too acheter kamasexpensive.Obama, dofus kamaswho is in the middlekamas dofusacheter des kamasof a multi-statedofus kamas tour to promote his kamas dofushealthcare policies, buy kamasalso accused "special dofus kamaskamas dofusinterests" of misleadingffxi gil Americans about aspectsfinal fantasy xi gilbuy ffxi gil of the reform bills making maple story mesostheir way through maplestory mesosCongress."These are the runescape goldrunescape moneystories that aren'taoc gold being told - stories age of conan goldof a healthcare age conan goldsystem that.
sajiannn (222.212.43.xxx) 2009-08-20 08:22:52

WASHINGTON, Augworld of warcraft goldcheap wow goldwow orwow power leveling 14 (Reuters) - Scrutinywow po of an air traffic achat gold wowwow levelingcontroller's wow oractions, including wow gold cheapwhether a phone callbuy wow gold may have distractedworld of warcraft goldwow gold cheapwow level him, intensified on wow geldFriday as investigators wow gold kaufenwow powerlevelingreleased new details wow gold buyabout the deadly collisionwow gold cheapwow leveling of a small plane and world of warcraft golda tourist helicopter wow powow orover New York's Hudson buy wow goldcheap wow goldwow power levelingwow powerlevelingRiver last week.dofus kamaskamas dofusDisclosures about Lord of the Rings Online GoldLOTRO GoldLOTR Goldhow controllers handledflyff money the Piper PA-32 aircraftflyff penya over a period of buy flyff goldminutes also ffxi gilsparked an open controversbuy ffxi gilFinal Fantasy XI gilbuy Warhammer gold between safetyWarhammer gold regulators and accidentEverQuest 2...
sajiannn (222.212.43.xxx) 2009-08-20 08:27:05

Make Peace ImperfectionI've yet world of warcraft goldwow power levelto meet an absolute cheap wow goldperfectionist whose wow power levelingwow powerlevelinglife was filled with inner buy wow goldpeace. The need for perfectionfinal fantasy gilcheap ffxi gilffxi gil and the desire for Maple Story Mesosmaplestory MesosMaple Story mesoinner tranquility conflicLOTRO GoldLOTR Goldlord of the rings golddofus kamas with each other. kamas dofusrunescape goldWhenever we are runescape moneyattached to having something rs moneyEverQuest 2 goldeq2 platflyff penyaa certain way, better flyff hack penyaflyff moneythan it already is, we are, EverQuest plateq platEverQuest goldalmost by definition, engaged in a eq2 platlosing battle.Rather than being flyff penyaeve iskcontent and grateful for what we have, we are world of warcraft goldbuy wow goldcheap wow goldfocused on
Women
Buy Ugg Boots (220.161.165.xxx) 2010-02-27 02:42:08

With all the
boots [url=http://www.zhjugg.com/new-product-ugg-bailey- 

button-58
03-grey-boots-p-]UGG Bailey Button Grey[/url] included in Ugg


Australia’s Classic Collection range the Bailey

Button is
lined ugg cardy

oatmeal with twin faced Grade A sheepskin. Also
there is the

UGG Bailey Button traditional

suede heel guard to ensure that not only

is this area
protected but offers this part of the boot support.

Ugg Cardy Boots Plus within the

boots you find each pair has sock liners

that are
made from sheepskin PU foam so increasing the level of

Ugg Cardy comfort a person feels

when wearing them.
MBT Shoes
mbt uk (220.161.165.xxx) 2010-02-27 05:31:02

When you purchase Mbt shoes you achieve shoes that appeal

mbt shoes to your sense of style while insuring a

shoe that does not cause pain
and discomfort after a day

mbt trainers shoes
of being on your feet. And after your purchase you know you

have shoes
that are going to outlast shoes found in most stores. Created
for comfort

and long lasting, MBT shoes utilize the highest
quality leather and materials. If you 

experience mbt uk discomfort from your foot

perspiring during the day MBT Shoes
applies a sock lining in the lining of the shoe

where you foot rests. mbt shoe This allows your feet

to stay dry during the most challenging active
days.hlm
激安 ユニフォ&
激安 ユ| (220.161.165.xxx) 2010-02-27 06:29:51

LCZ 
読売巨人軍は 、ビ
;ジターゲ&# 12540;ムで着用&
#12377;  427;夏季限定のӎ 0;|
69;マービジタ ーユニホ
;ーム&# 12301;を 採用しま
2377;。ユニフォーム...このユニ

ホӦ 0; ムの
発表会見&# 12364;12日(&#
26376;A 289;、東京・大৔ 3;ஹ
0;の球団事務 所で開か
れ、&# 12481;ームを代表  
375;て 坂本勇人選手&# ...
Paul Smith (220.161.165.xxx) 2010-02-27 06:59:18

Our store offer the cheap paul smith for you,sale new Paul Smith Shoes,and we will give my best server to you.Come on, more order will get more
discount.You can not miss them!rlh
nike-shox (125.78.242.xxx) 2010-02-27 12:39:56

rr
Today, the nike shox basketball shoes

are popular around the world. wholesale nike shox shoes

started out as an American company, but have since expanded around the
globe. They're now available in 120 countries. shox r4

with an emphasis on walking shoes, the engineers at New Balance know
the importance of a proper fit and offer a wide range of widths
and sizes. Often recommended by podiatrists, nike running shoes

take an "endorsed by no one" stance, preferring to let their
technology and comfort sell their shoes instead of paying a
celebrity athlete to do it for them. Additionally, nike shox monster

are available in a variety of styles, each designed for different
needs-motion control, extra support, off road, use etc. New Balance
makes running, walking, tennis, cross-training and basketball shoes
for men and women, and also offers a line of kids' ...
nike (220.161.165.xxx) 2010-02-27 12:59:12

mm
Apparently, 21,000 boots imported by Timberland from Thailand have lead paint on the insole, violating federal lead paint
rules. I'm guessing this paint was used for printing of the
logo inside the boot. Please note Dear Readers, these are Timberland waterproof and children are particularly sensitive to the effects of lead and lead
poisoning. Avoid a lead paint accident that could injure or hurt
your child.
When I first saw this I thought, "How do you make Timberland work boots? Where's the risk of accident or injury?" Then I read further and saw,
"lead paint." The headline reads:"Timberland Recalls Timberland for kids Due to Violation of Lead Paint Standard"The U.S. Consumer Product
Safety Commission announced a voluntary recall of these boots.
Consumers should stop using recalled products immediately.
mbt walking shoes (59.58.157.xxx) 2010-02-27 15:56:35

ZSM
MBT: The idea of mbt shoe Physiological Footwear
MBT, Masai Barefoot mbt walking shoes Technology, was invented by

Swiss engineer Karl Müller mbt shoes sale . During a visit to Korea

he made the startling mbt sale discovery that walking barefoot mbt masai shoes over paddy fields alleviated his back pain mtb shoes . Back in Switzerland, Müller began to develop a footwear

technology
that would make the natural instability mbt footwear of

soft ground such as Korean paddy fields discount mbt shoes or the

East African savannah accessible also to those, mbts shoes who have

to walk on hard surfaces. In 1996, after years spent mbt lami shoes on research and development, Masai Barefoot Technology was mature enough
to be
mbt walking shoes (59.58.157.xxx) 2010-02-27 16:01:51

ZSM
MBT: The idea of mbt shoe Physiological Footwear
MBT, Masai Barefoot mbt walking shoes Technology, was invented by

Swiss engineer Karl Müller mbt shoes sale . During a visit to Korea

he made the startling mbt sale discovery that walking barefoot mbt masai shoes over paddy fields alleviated his back pain mtb shoes . Back in Switzerland, Müller began to develop a footwear

technology
that would make the natural instability mbt footwear of

soft ground such as Korean paddy fields discount mbt shoes or the

East African savannah accessible also to those, mbts shoes who have

to walk on hard surfaces. In 1996, after years spent mbt lami shoes on research and development, Masai Barefoot Technology was mature enough
to be
chanel-handbags (59.58.157.xxx) 2010-02-27 16:08:48

ZSM
At $528 it is chanel handbags 2009 way out of my budget, so I think I’ll
drag chanel designer handbags my studded Kooba bag out of the closet for chanel
handbag a week or so and hope it helps me forget replica chanel handbags about
the Streetslight bag.
coach-handbag-c (59.58.157.xxx) 2010-02-27 16:12:10

ZSM
handbags snap closure, and silver-tone buckle embellishments. coach handbag outlet Double rolled straps and silver-tone hardware coach bag feet on the bottom of the bag coach leather handbag provide added durability. This chic tote is perfect for coach signature handbag everyday use and adds subtle
cheap jerseys (59.58.157.xxx) 2010-02-27 16:12:36

ZSM
With the survival cheap jerseys of people longer in the community, you will find 

that memories authentic jerseys are the most valuable when to turn around. If 

there are no cheap jerseys memories with a companion, then how we will to spend

our old age,
lonely nfl jersey life? I have all of the

most unforgettable memories are treasures on
this NFL nfl 

football jerseys jersey, which is made from 100%
nylon diamond back mesh body and Nylon dazzle sleeves and yoke. These football jerseys factors played a very important role in keeping the time.
Only registered users can write comments!

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

 
Next >
 
 
(C) 2010 daniel hary prasetyo
Free Joomla Template designed by funky-visions.de
 

articles (a-z order)