ASP.NET: Custom AutoCompleteTextBox WebControl

王朝asp·作者佚名  2006-11-24
宽屏版  字体: |||超大  

这是一个Teddy最近封装的AutoCompleteTextBox。我们知道,ASP.NET本身的TextBox也是支持一定的AutoComplete功能的,但是那是依赖浏览器实现的,并不能指定自定义的AutoComplete候选项。本文列举的AutoCompleteTextBox则弥补了这个缺憾。只需设置AutoCompleteTextBox.AutoCompleteData属性,传递一个string[],就能使TextBox支持自定义候选项了。

AutoComplete逻辑

如果没有匹配当前输入的候选项,则同一般的TextBox;如果只有一个候选项与当前输入匹配,则自动完成;如果有超过一个候选项与当前输入匹配,则在textbox中自动完成第一个候选项,并弹出包含所有候选项的弹出框。

实现源码

源码是在VS2005编译的,不过实际上几乎没有使用依赖2.0的语法,在vs2003下经极少修改就同样能编译的。

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace Ilungasoft.Framework.Web.UI.WebControls

{

[ToolboxData("<{0}:AutoCompleteTextBox runat=server></{0}:AutoCompleteTextBox>")]

public class AutoCompleteTextBox : WebControl

{

Private Members#region Private Members

private TextBox textBox = new TextBox();

private HtmlGenericControl autoCompleteFrame = new HtmlGenericControl();

private string ToJsStringArray(params string[] strs)

{

if (strs != null && strs.Length > 0)

{

StringBuilder sb = new StringBuilder();

sb.Append(" new Array(");

foreach (string str in strs)

{

sb.Append(string.Format("'{0}', ", str.Replace("'", "\'")));

}

return sb.ToString().TrimEnd(',', ' ') + ");";

}

else

{

return " new Array;";

}

}

private string MakeUniqueID(string id)

{

if (id != null && id.Trim().Length > 0)

{

return string.Concat(this.UniqueID.Replace("$", "_"), "_", id);

}

else

{

return this.UniqueID.Replace("$", "_");

}

}

#endregion

Properties#region Properties

[Bindable(true)]

[Category("Appearance")]

[DefaultValue("")]

[Localizable(true)]

public string Text

{

get

{

if (Page.IsPostBack)

{

textBox.Text = Page.Request.Form[MakeUniqueID("textBox")];

}

return textBox.Text;

}

set

{

textBox.Text = value;

}

}

[Bindable(true)]

[Category("Behavior")]

[DefaultValue("")]

[Localizable(true)]

public int MaxLength

{

get

{

return textBox.MaxLength;

}

set

{

textBox.MaxLength = value;

}

}

[Bindable(true)]

[Category("Behavior")]

[DefaultValue(false)]

[Localizable(true)]

public bool ReadOnly

{

get

{

return textBox.ReadOnly;

}

set

{

textBox.ReadOnly = value;

}

}

&n

[1] [2] [3] [4] [5] [6] 下一页

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有