如何在ASP.NET中创建自动完成TextBox?

如何在C#中创建一个绑定到数据源的自动完成 TextBox?

您可以使用jQuery自动完成或ASP.NET AJAX工具包自动完成

我使用ajaxcontrol工具包的AutoComplete

试试这个:.aspx页面

    

现在要从数据库自动填充:

 public static List GetCompletionList(string prefixText, int count) { return AutoFillProducts(prefixText); } private static List AutoFillProducts(string prefixText) { using (SqlConnection con = new SqlConnection()) { con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; using (SqlCommand com = new SqlCommand()) { com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'"; com.Parameters.AddWithValue("@Search", prefixText); com.Connection = con; con.Open(); List countryNames = new List(); using (SqlDataReader sdr = com.ExecuteReader()) { while (sdr.Read()) { countryNames.Add(sdr["ProductName"].ToString()); } } con.Close(); return countryNames; } } } 

现在:创建一个存储过程,根据自动完成文本框中的选定产品获取产品详细信息。

 Create Procedure GetProductDet ( @ProductName varchar(50) ) as begin Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName End 

创建函数名称以获取产品详细信息::

 private void GetProductMasterDet(string ProductName) { connection(); com = new SqlCommand("GetProductDet", con); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@ProductName", ProductName); SqlDataAdapter da = new SqlDataAdapter(com); DataSet ds=new DataSet(); da.Fill(ds); DataTable dt = ds.Tables[0]; con.Close(); //Binding TextBox From dataTable txtbrandName.Text =dt.Rows[0]["BrandName"].ToString(); txtwarranty.Text = dt.Rows[0]["warranty"].ToString(); txtPrice.Text = dt.Rows[0]["Price"].ToString(); } 

自动回发应该是真的

  

现在,只需调用此函数即可

 protected void TextBox1_TextChanged(object sender, EventArgs e) { //calling method and Passing Values GetProductMasterDet(TextBox1.Text); } 

1 – 通过Nugget轻松安装AjaxControl Toolkit

 PM> Install-Package AjaxControlToolkit 

2 – 然后在标记中

     

代码隐藏3:获取建议

 [System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()] public static string[] GetCompletionList(string prefixText, int count, string contextKey) { // Create array of movies string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"}; // Return matching movies return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray(); } 

来源: http : //www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx

aspx页面编码

 

.cs页面编码

 protected void Page_Load(object sender, EventArgs e) { autocomplete(); } protected void autocomplete() { Database p = new Database(); DataSet ds = new DataSet(); ds = p.sqlcall("select [name] from [stu_reg]"); int row = ds.Tables[0].Rows.Count; string abc=""; for (int i = 0; i < row;i++ ) abc = abc + ""; datalist1.InnerHtml = abc; } 

这里的数据库是一个文件(Database.cs),我在其中创建了名为sqlcall的方法,用于从数据库中检索数据。