摘要:[VB][jQuery] 使用 jQuery.autocomplete 實現自動完成文字框
也是工作上有使用到,紀錄一下這個 autocomplete 配合 asp.net 的實現方法
bassistance.de autocomplete 下載網址
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
bassistance.de autocomplete Demo網址
http://jquery.bassistance.de/autocomplete/demo/
看了一下bassistance.de的autocomplete以經停止更新了,不過沒關係能用就好
下載好檔案之後會有以下這些
裡有面一個範例檔,有大概簡單的用法可以先看一下。
之後取出要用的檔案,放到你的專案下。
接下來我把這個方法包成了一個ascx方便使用,方法如下
建立兩個檔案 test.ascx / ajaxGetData.aspx
test.ascx 為一個元件, ajaxGetData.aspx 此頁是取得資料的頁面
test.ascx
test.ascx.vb
Partial Class formobj_test
Inherits System.Web.UI.UserControl
Dim _tblname As String = ""
Dim _colname As String = ""
WriteOnly Property tblname() As String
Set(ByVal value As String)
_tblname = value
End Set
End Property
WriteOnly Property colname() As String
Set(ByVal value As String)
_colname = value
End Set
End Property
Property Text() As String
Get
Return txtAutoBox.Text.Trim
End Get
Set(ByVal value As String)
txtAutoBox.Text = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
hfTbl.Value = _tblname
hfCol.Value = _colname
End Sub
End Class
ajaxGetData.aspx
只需保留 <%@ Page Language="VB" AutoEventWireup="true" ..........%> 這個標籤就好。
ajaxGetData.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Partial Class formobj_ajaxAutocomplete_ajaxGetDate
Inherits System.Web.UI.Page
Dim qryStr As String = ""
Dim qryTbl As String = ""
Dim qryCol As String = ""
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not String.IsNullOrEmpty(Request.QueryString("q")) Then
Dim jStr As New List(Of String)
Dim ds As New DataSet
qryStr = Request.QueryString("q")
qryTbl = Request.QueryString("t")
qryCol = Request.QueryString("c")
ds = GetObject(qryStr, qryTbl, qryCol)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
jStr.Add(String.Format("{0}|{1}", ds.Tables(0).Rows(i).Item(qryCol).ToString.Trim, ds.Tables(0).Rows(i).Item(qryCol).ToString.Trim))
Next
Response.Write(String.Join(vbLf, jStr.ToArray))
Response.End()
End If
End Sub
Public Function GetObject(ByVal q As String, ByVal t As String, ByVal c As String) As DataSet
Dim myConnection As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connectionString"))
Dim myCommand As New SqlCommand("select * from " & t & " where " & c & " like '" & q & "%'", myConnection)
'myCommand.Parameters.Add("@", SqlDbType.Char, 5).Value = q & "%"
myConnection.Open()
Dim myAdapter As New SqlDataAdapter(myCommand)
Dim myDataSet As New DataSet
myAdapter.Fill(myDataSet)
myConnection.Dispose()
Return myDataSet
End Function
End Class
參數q: 為輸入要查詢的文字是固定的
而另外參數 t 跟 c 是我另外加上去的,是用來取得Page頁自訂的資料表名跟欄位名稱,才能達到包成ascx可以通用的情況。
完成的樣子就如下圖
以上只是大概的用法..要詳細的用法請去bassistance.de網站內看。
以上文章敘述如有錯誤及觀念不正確,請不吝嗇指教
如有侵權內容也請您與我反應~謝謝您 :)