我是ASP.NET新手,我在我的應用程序中使用AJAX製作搜索框。無法從數據表中填充列表框(自動完成文本框)
例如:如果用戶在文本框中輸入「abc」,那麼文本框將從數據庫中獲取以「abc」開頭的數據。
,然後我要顯示所有與abc
ListBox中開始,我獲取DataTable中的數據,以及數據在數據表中正確地來的字符串,
如何從數據表中填寫我的列表框?
這裏是我的代碼片段,在SecrchBox.aspx
代碼 onkeyup i am calling this getdata()
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SearchBox.aspx.cs" Inherits="SearchBox" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" language="javascript">
function getdata() {
var TextBox1 = document.getElementById("<%= TextBox1.ClientID %>");
var ltrSearchResults = document.getElementById("<%= ltrSearchResults.ClientID %>");
var str = TextBox1.value;
var xmlhttp;
if (str.length == 0) {
ltrSearchResults.innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "Newpage.aspx?q=" + str, false);
xmlhttp.send();
ltrSearchResults.innerHTML = xmlhttp.responseText;
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox><br />
<asp:Label runat="server" ID="Label1" ></asp:Label><br />
</div>
</form>
</body>
</html>
代碼,aspx.cs
public partial class Newpage : System.Web.UI.Page
{
public string ConnectionString = "Data Source=ilsql;Initial Catalog=krunal_DB;User ID=krunaldbuser;[email protected];";
string[] symbol=new string[2170];
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}
private void GetData()
{
if (Request.QueryString["q"] != null)
{
string Value = Convert.ToString(Request.QueryString["q"]);
StringBuilder str = new StringBuilder();
// string str;
if (Value.Length > 0)
{
SqlConnection cn = new SqlConnection(ConnectionString);
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '%" + Value + "%'", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Close();
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
str.Append(Convert.ToString(dr["Scrip"]) + "<br>");
}
str = str.Remove(str.Length - 2, 2);
}
Response.Write(str.ToString());
}
else
{
Response.Write("No Result Found");
}
}
}
}
任何幫助將appriciated!
在此先感謝。
使用的WebMethod這一點。使用此鏈接:http://www.aspsnippets.com/Articles/ASPNet-AJAX-AutoCompleteExtender-Pass-Additional-Parameter-to-WebMethod-using-ContextKey.aspx – 2012-04-13 05:55:37