ASP DropDownList/List Menu From Database |
ASP DropDownList/List Menu From Database เป็นตัวอย่างการ เขียน ASP เพื่อดึงข้อมูลจาก Database มาใส่ใน DropDownList หรือ List Menu
Sample
AspListMenuDatabase1.asp
<html>
<head>
<title>ThaiCreate.Com Tutorial</title>
</head>
<%
Dim Conn,strSQL,objRec
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("db/mydatabase.mdb"),"" , ""
%>
<body>
<form action="AspListMenuDatabase2.asp" method="post" name="form1">
List Menu<br>
<select name="lmName1">
<option value=""><-- Please Select Item --></option>
<%
strSQL = "SELECT * FROM customer "
Set objRec = Server.CreateObject("ADODB.Recordset")
objRec.Open strSQL, Conn, 1,3
While Not objRec.EOF
%>
<option value="<%=objRec.Fields("CustomerID").Value%>"><%=objRec.Fields("CustomerID").Value & " - " & objRec.Fields("Name").Value%></option>
<%
objRec.MoveNext
Wend
%>
</select>
<input name="btnSubmit" type="submit" value="Submit">
</form>
</body>
</html>
<%
objRec.Close()
Conn.Close()
Set objRec = Nothing
Set Conn = Nothing
%>
AspListMenuDatabase2.asp
<html>
<head>
<title>ThaiCreate.Com Tutorial</title>
</head>
<%
Dim Conn,strSQL,objRec
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("db/mydatabase.mdb"),"" , ""
%>
<body>
<%
Response.write Request.Form("lmName1")
Response.write "<hr>"
strSQL = "SELECT * FROM customer WHERE CustomerID = '"&Request.Form("lmName1")&"' "
Set objRec = Conn.Execute(strSQL)
Response.write objRec.Fields("Name").Value
%>
</body>
</html>
<%
objRec.Close()
Conn.Close()
Set objRec = Nothing
Set Conn = Nothing
%>
หรือในกรณีที่ต้องการกำหนดค่า default ค่าเก่าจาก Database ก็สามารถทำได้เช่นเดียวกันครับ
AspListMenuDatabase3.asp
<html>
<head>
<title>ThaiCreate.Com Tutorial</title>
</head>
<%
Dim Conn,strSQL,objRec,strDefault,strSel
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("db/mydatabase.mdb"),"" , ""
strDefault = "C003"
%>
<body>
<form action="AspListMenuDatabase3.asp" method="post" name="form1">
List Menu<br>
<select name="lmName1">
<option value=""><-- Please Select Item --></option>
<%
strSQL = "SELECT * FROM customer "
Set objRec = Server.CreateObject("ADODB.Recordset")
objRec.Open strSQL, Conn, 1,3
While Not objRec.EOF
If strDefault = objRec.Fields("CustomerID").Value Then
strSel = "selected"
Else
strSel = ""
End IF
%>
<option value="<%=objRec.Fields("CustomerID").Value%>" <%=strSel%>><%=objRec.Fields("CustomerID").Value & " - " & objRec.Fields("Name").Value%></option>
<%
objRec.MoveNext
Wend
%>
</select>
<input name="btnSubmit" type="submit" value="Submit">
</form>
</body>
</html>
<%
objRec.Close()
Conn.Close()
Set objRec = Nothing
Set Conn = Nothing
%>
|