来源:www.cncfan.com | 2006-1-25 | (有2218人读过)
(Page 4 of 5 )
The following function provides a real life example of a common ASP task. Customer Spec: "The job is to create a drop-down box on my webpage using values from my database table. The table is called tbl_fruit and lists different types of fruit. Take a look at the table below as an example. Oh yes, I might need the drop down to sit inside a form with other input fields."
fruit_id fruit_name 1 Apple 2 Pear 3 Orange
The solution is to develop a function named "db_dropdown" which we’ll call in our script just as we did with the simplemaths function earlier.
The function will carry out the following tasks (which could be further broken down into more functions if we choose to do so):
Open a new HTML dropdown box definition
Query the database table using an open connection. (This opens a recordset object).
Create an option for each record in the recordset result in a single drop-down box
Close the recordset connection
Close the HTML dropdown box definition <% function db_dropdown(dbconnection, tablename, bound_field, display_field) ' output the HTML code to initialise a drop-down box response.write "<select name='"&bound_field&"' id='"&bound_field&"'>"
' open recordset connection strSQL="SELECT " & bound_field & "," & display_field & " FROM " & tablename set xrs=server.createobject("adodb.recordset") xrs.open strSQL, dbconnection do while not xrs.eof ' for each line record, write an option to the drop-down box response.write "<option value='"&xrs(0)& "'>"& xrs(1)& "</option>" xrs.movenext loop 'clear up the connections xrs.close set xrs=Nothing
' output the HTML code to close the drop-down box response.write "</select>" end function %>
That’s the function, ready to go. It might not be perfect yet, but because we only need to write it once and we’ll maintain it in one place we can perfect it later. It’s a good idea to keep all of your functions in one place. If you’re familiar with using "Include Files" that’s a great option – if not, then you have some more reading to do! Again it comes down to maintainability. If you have one copy of each of the functions kept in one central file it’s easy to update if necessary.
|