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

Please help me. I want to search a item while typing. The code is working fine and I need to enter it so that it will view the item that I want to see. Can you help me? I think the latter part has the problem or has missing codes.

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();

        }
    }
}````

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the jquery to make the autocompleted textbox.

First, please remove the code in your App_Start/RouteConfig.

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

Second, you can refer to the following html code in your webform.aspx file.

<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>

Third, please define the webmethod in your webform.aspx.cs file

[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 ''<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="604b20330501120308250d102e010d05">[email protected]</a>+'%'";
                    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;
                }
            }
        }

Note: Please note that we need to use the same parameter in the html and c# code. Like WebForm1.aspx/GetEmployeeName and empName.

Finally, you can see the result:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x