我正在尝试使用数据库中的名称自动填写文本框。当我在运行时输入文本框时没有任何反应。 我一直在关注本教程,但无法使其正常运行。 http://www.dotnetodyssey.com/2015/01/14/autocomplete-textbox-using-jquery-asp-net-querying-database-complete-example/
下面的源代码。
Aspx页面:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(document).ready(function () {
$("#txtNames").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm1.aspx/GetNames",
data: "{'namePrefix':'" + $("#txtNames").val() + "'}",
dataType: "json",
minLength: 2,
success: function (data) {
response(data.d)
},
error: function (response) {
alert("Error" + res.responseText);
}
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="txtNames">Names:</label>
<asp:TextBox ID="txtNames" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
守则背后:
[WebMethod]
public static string[] GetNames(string namePrefix)
{
List<string> Name = new List<string>();
DataTable dtNames = new DataTable();
string sqlQuery = "select distinct Name from Houses where Name like '" + namePrefix + "%'";
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(dtNames);
foreach (DataRow row in dtNames.Rows)
{
string name = Convert.ToString(row["Name"]);
Name.Add(name);
}
}
catch (Exception ex)
{
throw ex;
}
return Name.ToArray<string>();
}
答案 0 :(得分:0)
以下是自动填充文本框的示例:
private void LoadServices()
{
txtServiceName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtServiceName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtServiceName.AutoCompleteCustomSource = colValues;
}
和
AutoCompleteStringCollection colValues = new AutoCompleteStringCollection();
private void GetAllServices()
{
// get list of Windows services
ServiceController[] services = ServiceController.GetServices();
List<string> ac = new List<string>();
// try to find service name
foreach (ServiceController service in services)
{
ac.Add(service.ServiceName.ToString());
}
colValues.AddRange(ac.ToArray());
}