ASP.NET Event Handlers Database -> Browser ->Shopping Basket Validators.

33
ASP.NET Event Handlers Database -> Browser - >Shopping Basket Validators

Transcript of ASP.NET Event Handlers Database -> Browser ->Shopping Basket Validators.

ASP.NETEvent Handlers

Database -> Browser ->Shopping Basket

Validators

Event Handlers

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

• In some cases you know when the event will happen– e.g. Page_Load

• Most of the time it is user driven– e.g. Button1_Click

Common handlers

• Onclick• Onselect• Onselectedindexchanged• Onmouseover• Onsubmit

Can’t cope with overly complex calls

CommandEventArgsThis is the key to determining which button was

pressed inside an ASP.NET Form

Allows you to use the properties• CommandArgument• CommandName

More specialised versions available:• DataListCommandEventArgs• DataGridCommandEventArgs

Example 1 - In the Web Control<asp:Button id="Button1" Text="Sort"

CommandName="Sort"CommandArgument="Ascending"OnCommand="Command_Button_Click" runat="server"/>

<asp:Button id="Button2" Text=“Submit"CommandName=“Submit"OnCommand="Command_Button_Click" runat="server"/>

Example 1 - Event HandlerSub CommandButton_Click(sender As Object, e As

CommandEventArgs) Select e.CommandName

Case "Sort" Sort_List(CType(e.CommandArgument, String))

Case "Submit" Message.Text = "You clicked the Submit

button" Case Else

Message.Text = "Command name not valid." End Select

End Sub

DataGrid CommandEventArgs

• ItemCommand– Generic event– raised whenever any button associated with an item in the

DataGrid is clicked. – provides for programmatically determining which specific

command button is clicked and take appropriate action– commonly used to handle custom command buttons for the

DataGrid control.

• DeleteCommand, CancelCommand, EditCommand, UpdateCommand– Events raised whenever the corresponding cancel, delete, edit, or update button associated with an item in the DataGrid is clicked.

Example DataGrid delete event Sub Delete_Item(s As Object, e As DataGridCommandEventArgs) objDT = Session("Cart") objDT.Rows(e.Item.ItemIndex).Delete() Session("Cart") = objDT End Sub

<asp:DataGrid id="dg" runat="server" ondeletecommand="Delete_Item">

<columns> <asp:buttoncolumn buttontype="LinkButton“

commandname="Delete" text="Remove Item" /> </columns></asp:DataGrid>

Example DataList Event1 – in the web control

<asp:DataList id="mypatients" runat="server">

<ItemTemplate><P>NHS No.: <%# Container.DataItem("P_NHS") %><P>Name :<%# Container.DataItem("P_Fname")%><%# Container.DataItem("P_Lname")%> <asp:Button ID="btnAdd" runat="server" Text="Add” CommandName="Cart" />

</ItemTemplate></asp:DataList>

Example DataList event2 – event handler

Sub mypatients_ItemCommand(s As Object, e As DataListCommandEventArgs) Handles mypatients.ItemCommand

If e.CommandName = "Cart" Then‘whole bunch of programming goes here

demonstrated laterEnd If

End Sub

Database -> DataList -> Shopping Cart

1. Use a SELECT query to retrieve data and bind it to the datalist

2. Put a button in the datalist with CommandName=“Cart”

3. Write an event handler for the datalist– Takes information from the list – Puts information into new row of table stored in

Session

Event handler for datalist

Sub mypatients_ItemCommand(s As Object, e As DataListCommandEventArgs) Handles mypatients.ItemCommand

If e.CommandName = "Cart" ThenNOW WE WRITE THIS BIT

End IfEnd Sub

If CommandName=“Cart”1. Retrieve the shopping cart from

the session2. Create a new row3. Retrieve information from the

relevant row of the datalist4. Put the information from the

datalist into the new row5. Put the new row on the bottom of

the cart table6. Put the table back into the session

This is the onlynew bit you havenot seen before

<%#Container.DataItem(“something”)%>

– Displays on screen, but can’t be used programmatically

<asp:Label id=“stuff” text=‘<%#Container.DataItem(“something”)%>’Runat=“server” />

– Now the info from the container is associated with an object that has an ID that we can use, e.g:

stuff.Text

3 – retrieve data from relevant row of datalist

If e.CommandName = "Cart" Then

Dim temp as Label = e.Item.FindControl(“stuff")

Dim quantity As TextBox = e.Item.FindControl(“amount”)

End If

So you put temp.Text and quantity.Text into the new row for the shopping cart

Explanation of code for step 3• e

– DataListCommandEventArg that we passed in– Essentially all the objects from the row of the datalist

that was clicked on

• e.Item– Used to address a specific object in the EventArgs

• e.Item.FindControl– Used to find a specific NAMED object in the EventArgs.

In this case a specific label & a specific textbox

Images in the DataList

<asp:Image ID=“mugshot” runat=“server”ImageUrl='<%#DataBinder.Eval(Container.DataItem,

“P_Picture")%>‘ >

Where P_Picture is a column in the table that contains the filename for the picture e.g. pic1.jpg

• Compares the value of one input to another input or to a fixed value

• If the input is empty, the validation will succeed– You need to make the field required to solve this

problem

Compare Validator

Example Comparison Validation<form runat="server">

<h4>Enter your password: </h4><P><asp:TextBox id="txt1" runat="server" /><P><asp:TextBox id="txt2" runat="server" /><asp:Button Text="Validate" runat="server" /><asp:CompareValidator id="compval"

Display="dynamic"ControlToValidate="txt1"ControlToCompare="txt2"ForeColor="red“ BackColor="yellow"Type="String"EnableClientScript="false"Text="Validation Failed!" runat="server" />

</form>

Output

Range Validation

• Checks that the user enters a value that falls between two values

• Ranges can be within numbers, dates, or characters.

• Does not fail if the input is empty.– Solve this by making the input required

• Does not fail if the input value cannot be converted to the data type specified.– Combine with CompareValidator to solve this

Example Range Validation<form runat="server"><P>Enter a grade from 1 to 20:

<asp:TextBox id="tbox1" runat="server" /><br /><asp:Button Text="Submit" OnClick="submit" runat="server" /><br /><asp:Label id="lbl1" runat="server" /><br /><asp:RangeValidator ControlToValidate="tbox1"MinimumValue="1“ MaximumValue=“20"Type="Integer“ EnableClientScript="false"Text="The value must be from 1 to 20" runat="server" /></form></body></html>

Output

Regular Expression Validator

• Ensures that the value of an input matches a specified pattern

• Does not fail if the input is empty– Make the input required to solve this

Example Regular Expression Validation<form runat="server"> Enter your credit card number: <asp:TextBox id="txtbox1" runat="server“/> <br /> <asp:Button id="Button1" runat="server" text="Submit“ /> <br /> <asp:RegularExpressionValidator id=“REV1" runat="server“

EnableClientScript="false" ControlToValidate="txtbox1" ErrorMessage="The card number must be 16 digits long" ValidationExpression="\d{16}“ />

</form>

Output

Required Field Validator

• Ensures user has input some data

• Leading and trailing spaces of the input value are removed before validation.

Example Required field validation

<form runat="server"> Name: <asp:TextBox id="name" runat="server“ /> <br /> Email: <asp:TextBox id="email" runat="server“ /> <br /> <asp:Button id="Button1" runat="server" Text="Submit“ /> <br /> <asp:RequiredFieldValidator id="RFV1" runat="server" Text="Your E-mail address is required" ControlToValidate="email“ /> </form>

Output

Alternative Output

Other Validation Controls

• ValidationSummary– Displays a report of all validation errors occurred

in a Web page

• CustomValidator– Write your own

Examples

Code demonstrated in lecture will go on the ASP.NET section of the discussion board

http://wwww.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp

TO DO

• Oasisplus– Shopping Basket Activity

– Coursework

• NEXT WEEK– JavaScript