使用 ASP.Net 在搜索框中输入内容时如何显示特定的 item/s?

How I can show specific item/s when typing in search box using ASP.Net?

请帮帮我。我想在打字时搜索项目。该代码运行良好,我需要输入它以便它可以查看我想查看的项目。你能帮助我吗?我觉得后半段有问题或者漏码

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Data;

namespace IT22_OE2
{
    public partial class AdminDashboard : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string con = "Server =localhost; Uid=root; password= ; persistSecurityInfo=True; database=mybank_db; SslMode=none";
            MySqlConnection mycon = new MySqlConnection(con);
            DataTable view = new DataTable();
            MySqlCommand com = null;

            try
            {
                com = new MySqlCommand("select * from depositors_tbl", mycon);
                mycon.Open();
                view.Load(com.ExecuteReader());
                mycon.Close();
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + " ')</script>");
                mycon.Close();
            }
            GridView1.DataSource = view;
            GridView1.DataBind();
        }

        protected void txtSearch_TextChanged(object sender, EventArgs e)
        {
            string con = "Server =localhost; Uid=root; password= ; persistSecurityInfo=True; database=mybank_db; SslMode=none";
            MySqlConnection mycon = new MySqlConnection(con);
            MySqlCommand cmd = new MySqlCommand();
            MySqlDataAdapter ada = new MySqlDataAdapter();
            DataTable view = new DataTable();
            MySqlCommand com = new MySqlCommand();

            mycon.Open();
            com = new MySqlCommand("select * from depositors_tbl where accountname like '%" + txtSearch.Text + "%' ", mycon);
            ada.SelectCommand = com;
            ada.Fill(view);
            //view.Load(com.ExecuteReader());
         

            GridView1.DataSource = view;
            GridView1.DataBind();
            ada.Update(view);
          
            mycon.Close();

        }
    }
}````

您可以使用 jquery 来制作自动完成的文本框。

首先,请删除您 App_Start/RouteConfig 中的代码。

public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            //settings.AutoRedirectMode = RedirectMode.Permanent; ->Remove this line code.
            routes.EnableFriendlyUrls(settings);
        }

其次,您可以在 webform.aspx 文件中参考以下 html 代码。

<head runat="server">  
    <title>Test</title>  
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
    <link rel="stylesheet" href="/resources/demos/style.css"/>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
      
    <script type="text/javascript">  
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $("#txtEmpName").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: '<%= ResolveUrl("WebForm1.aspx/GetEmployeeName") %>',
                        data: '{empName: "' + request.term + '"}',
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },  
                        error: function (result) {
                            alert("Invalid data")
                        }
                    });
                }
            });
        }
    </script>  
  
</head> 
<body>
    <form id="form1" runat="server">
       <div>
           <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
       </div>
    </form>
</body>

第三,请在您的 webform.aspx.cs 文件中定义 webmethod

[WebMethod(EnableSession = true)]
        public static List<string> GetEmployeeName(string empName)
        {
            List<string> empResult = new List<string>();

            using (SqlConnection con = new SqlConnection(@"Connstr"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select top 5 Name from Student where Name LIKE ''+@SearchEmpName+'%'";
                    cmd.Connection = con;
                    con.Open();
                    cmd.Parameters.AddWithValue("@SearchEmpName", empName);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        empResult.Add(dr["Name"].ToString());
                    }
                    con.Close();
                    return empResult;
                }
            }
        }

注意:请注意,我们需要在 html 和 c# 代码中使用相同的参数。比如 WebForm1.aspx/GetEmployeeNameempName.

终于可以看到结果了: