Populate multiple ASP.Net TextBoxes based on jQuery AutoComplete selection using C# and VB.Net

mahjoubi
 
on Jan 23, 2023 09:49 PM
435 Views

Hi members

I have a modal popup that with an autocomplete and postback enabled

When i want add a 2nd textbox to get implemented automatically

This is my code :

<asp:TextBox ID="TextBox3" runat="server" Width="205px" AutoPostBack="True"></asp:TextBox>
<asp:HiddenField ID="hfName" runat="server" />
<script type="text/javascript">
    $(function () {
        $("[id*=TextBox3]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    url: '<%=ResolveUrl("~/ArticleInvestigation.aspx/GetNames") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=hfName]").val(i.item.label);
                $.ajax({
                    type: "POST",
                    url: '<%=ResolveUrl("~/ArticleInvestigation.aspx/GetCountry") %>',
                    data: "{ 'name': '" + i.item.label + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $("[id*=TextBox4]").val(response.d);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            },
              select: function (e, i) {
                $("[id$=hfName]").val(i.item.label);
                $.ajax({
                    type: "POST",
                    url: '<%=ResolveUrl("~/ArticleInvestigation.aspx/GetMatricule") %>',
                    data: "{ 'name': '" + i.item.label + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $("[id*=TextBox6]").val(response.d);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            minLength: 0
        });
    });
</script>
Numero&nbsp; :
<asp:TextBox ID="TextBox4" runat="server" Width="82px"></asp:TextBox>
Public Shared Function GetNames(ByVal prefix As String) As String()
    Dim customers As List(Of String) = New List(Of String)()
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand()
            'cmd.CommandText = "SELECT CustomerId, Name FROM Customers WHERE Name LIKE @SearchText + '%'"
            cmd.CommandText = "select cbMarq,CT_Intitule from F_COMPTET where ct_type=0 and " & " CT_Intitule like @CT_Intitule + '%' order by CT_Intitule"
            cmd.Parameters.AddWithValue("@CT_Intitule", prefix)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    customers.Add(String.Format("{0}", sdr("CT_Intitule")))
                End While
            End Using
            conn.Close()
        End Using
    End Using
    Return customers.ToArray()
End Function

<WebMethod>
Public Shared Function GetCountry(ByVal name As String) As String
    Dim country As String = String.Empty
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand()
            'cmd.CommandText = "SELECT TOP 1 Country FROM Customers WHERE Name = @Name"
            cmd.CommandText = "select [CT_Num] from F_COMPTET where  CT_Intitule = @CT_Intitule"
            cmd.Parameters.AddWithValue("@CT_Intitule", name)
            cmd.Connection = conn
            conn.Open()
            country = Convert.ToString(cmd.ExecuteScalar())
            conn.Close()
        End Using
    End Using
    Return country
End Function
<WebMethod>
Public Shared Function GetMatricule(ByVal name As String) As String
    Dim Matricule As String = String.Empty
    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As SqlCommand = New SqlCommand()
            'cmd.CommandText = "SELECT TOP 1 Country FROM Customers WHERE Name = @Name"
            cmd.CommandText = "select [CT_Identifiant] from F_COMPTET where  CT_Intitule = @CT_Intitule"
            cmd.Parameters.AddWithValue("@CT_Intitule", name)
            cmd.Connection = conn
            conn.Open()
            Matricule = Convert.ToString(cmd.ExecuteScalar())
            conn.Close()
        End Using
    End Using
    Return Matricule
End Function

work perfectly with a one textbox not with 2 textbox

please help

Download FREE API for Word, Excel and PDF in ASP.Net: Download
AjayV
 
on Jan 24, 2023 02:18 AM
on Jan 25, 2023 06:18 AM

Hi mahjoubi,

Please refer below sample.

Database

I have made use of the following table Customers with the schema as follows. 

I have already inserted few records in the table.

You can download the database table SQL by clicking the download link below.

Download SQL file

HTML

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
    rel="Stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("[id*=txtName]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    url: '<%=ResolveUrl("~/Default.aspx/GetNames") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=hfName]").val(i.item.label);
                $.ajax({
                    type: "POST",
                    url: '<%=ResolveUrl("~/Default.aspx/GetCountry") %>',
                    data: "{ 'name': '" + i.item.label + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $("[id*=txtCountry]").val(response.d.split('-')[0]);
                        $("[id*=txtCustomerId]").val(response.d.split('-')[1]);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            minLength: 0
        });
    });
</script>
<div>
    <table>
        <tr>
            <td>
                Enter Name:
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server" />
            </td>
            <td>
                <asp:HiddenField ID="hfName" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Country:
            </td>
            <td>
                <asp:TextBox ID="txtCountry" runat="server" />
            </td>
            <td>
            </td>
        </tr>
        <tr>
            <td>
                CustomerId
            </td>
            <td>
                <asp:TextBox ID="txtCustomerId" runat="server"></asp:TextBox>
            </td>
        </tr>
    </table>
</div>

Namespaces

C#

using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;

VB.Net

Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient

Code

C#

[WebMethod]
public static string[] GetNames(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT CustomerId, Name FROM Customers WHERE Name LIKE @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}-{1}", sdr["Name"], sdr["CustomerId"]));
                }
            }
            conn.Close();
        }
    }
    return customers.ToArray();
}

[WebMethod]
public static string GetCountry(string name)
{
    string country = string.Empty;
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT TOP 1 Country+'-'+CAST(CustomerId AS VARCHAR(10)) FROM Customers WHERE Name = @Name";
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Connection = conn;
            conn.Open();
            country = Convert.ToString(cmd.ExecuteScalar());
            conn.Close();
        }
    }
    return country;
}

VB.Net

<WebMethod()>
Public Shared Function GetNames(ByVal prefix As String) As String()
    Dim customers As List(Of String) = New List(Of String)()

    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("conString").ConnectionString

        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = "SELECT CustomerId, Name FROM Customers WHERE Name LIKE @SearchText + '%'"
            cmd.Parameters.AddWithValue("@SearchText", prefix)
            cmd.Connection = conn
            conn.Open()

            Using sdr As SqlDataReader = cmd.ExecuteReader()

                While sdr.Read()
                    customers.Add(String.Format("{0}-{1}", sdr("Name"), sdr("CustomerId")))
                End While
            End Using

            conn.Close()
        End Using
    End Using

    Return customers.ToArray()
End Function

<WebMethod()>
Public Shared Function GetCountry(ByVal name As String) As String
    Dim country As String = String.Empty

    Using conn As SqlConnection = New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("conString").ConnectionString

        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = "SELECT TOP 1 Country+'-'+CAST(CustomerId AS VARCHAR(10)) FROM Customers WHERE Name = @Name"
            cmd.Parameters.AddWithValue("@Name", name)
            cmd.Connection = conn
            conn.Open()
            country = Convert.ToString(cmd.ExecuteScalar())
            conn.Close()
        End Using
    End Using

    Return country
End Function

Screenshot