DropDownList最大的好处是,将Text呈现给用户,而可以在后台将用户选择的Vaue值存储起来,但是当选项过多时,用户操作起来就比较困难。利用jquery.autocomplete制作智能感知文本框,可以很好的解决这个问题。下面以实例来演示实现过程。
1.在页面添加框架和样式表的引用。
<script src="Scripts/jquery-1.4.1.js" type="text/javascript" language="javascript"></script>
<script src="Scripts/jquery.autocomplete.js" type="text/javascript" language="javascript"></script>
<link href="Styles/jquery.autocomplete.css" type="text/css" rel="Stylesheet" />
2.在页面添加需要感知的文本框Text以及需要存储的文本框Value
<table>
<tr>
<td>名称:<asp:TextBox ID="txtmc" runat="server" onblur="changeText(this);" Width="150px"></asp:TextBox></td>
<td>编号:<asp:TextBox ID="txtbh" runat="server"></asp:TextBox></td>
</tr>
</table>
3.在页面Head部分添加如下jquery.autocomplete的调用代码。其中Autocomplete.aspx页面是在后面需要添加的新页面
<script type="text/javascript" language="javascript">
$(function () {
setAutoText();
})
function setAutoText() {
$("#txtmc").autocomplete("Autocomplete.aspx", {
//minChars: 0
//, autoFill: true
mustMatch: true
, matchContains: true
, cacheLength: 0, max: 20, width: 150
, extraParams: { type: function () { return "1"; } }
}).result(function (event, data, formatted) {
if (data) {
var vArr = data[0].split('..,');
if (vArr.length > 0) {
$("#txtbh").val(vArr[0]);
}
}
});
}
//以下函数处理当txtmc没有符合值时,在失去焦点后,自动清空txtbh中的内容
function changeText(obj) {
if (obj.value != '') {
var vArr = obj.value.split('..,');
if (vArr.length == 2) {
$("#txtbh").val(vArr[0]);
}
else {
$("#txtbh").val('');
}
}
else {
$("#txtbh").val('');
}
}
</script>
4.创建智能感知需要调用的页面Autocomplete.aspx,在Autocomplete.aspx.cs中添加如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Data.SqlClient;
public partial class Autocomplete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string result = string.Empty;
if (Request.QueryString["q"] != null)
{
if (!string.IsNullOrEmpty(Request.QueryString["q"].ToString()))
{
string strQuery = HttpUtility.UrlDecode(Request.QueryString["q"].ToString());
if (Request.QueryString["type"] != null)
{
string strType = HttpUtility.UrlDecode(Request.QueryString["type"].ToString());
result = getList(strQuery, strType);
}
}
}
Response.Write(result);
Response.End();
}
private string getList(string pQuery, string pType)
{
string strSql = string.Empty;
StringBuilder sb = new StringBuilder();
SqlConnection con = new SqlConnection(" ");
con.Open();
switch (pType)
{
case "1":
strSql = "SELECT TOP 10 bh,mc FROM cfg WHERE bh+'..,'+mc like '%" + pQuery + "%' order by mc ";
SqlDataAdapter sda = new SqlDataAdapter(strSql, con);
DataSet ds = new DataSet();
sda.Fill(ds);
DataTable dt = ds.Tables[0];
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append(dt.Rows[i]["bh"].ToString() + "..," + dt.Rows[i]["mc"].ToString());
sb.Append("\n");
}
}
break;
}
con.Close();
con.Dispose();
return sb.ToString();
}
}
运行效果如下: