Fill TextBox from database using jQuery Ajax on Select2 DropDownList selection

Dedzil
 
on Sep 30, 2022 05:59 AM
Sample_200262.zip
805 Views

Can you please help me with this.

Display data in TextBox from database on ASP.Net DropDownList selection using jQuery Ajax

If the DropDownList ClientMode is in static it doesn’t work. But I want to use select2 so that i can search in the DropDownList.

Below is my DropDownList tag.

<asp:DropDownList id="ddlClass" runat="server" cssclass="form-control" requide="true" ClientIDMode="Static"></asp:DropDownList>
Download FREE API for Word, Excel and PDF in ASP.Net: Download
KasimA
 
on Sep 30, 2022 07:47 AM
on Sep 30, 2022 07:49 AM

Hi Dedzil,

Plases refer below sample.

Database

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

Download SQL file

HTML

<asp:DropDownList ID="ddlCountries" runat="server" ClientIDMode="Static"></asp:DropDownList>
<asp:TextBox ID="txtOther" runat="server" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=ddlCountries]").select2();
        $("[id*=ddlCountries]").on('change', function () {
            var country = $("[id*=ddlCountries]").find("option:selected").text();
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetData",
                data: "{country:'" + country + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $('[id*=txtOther]').val(data.d.Name);
                },
                error: function (response) {
                    alert(response.responseText)
                }
            });
        });
    });
</script>

Namespaces

C#

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

VB.Net

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

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT Country FROM Customers", con))
            {
                con.Open();
                ddlCountries.DataSource = cmd.ExecuteReader();
                ddlCountries.DataTextField = "Country";
                ddlCountries.DataValueField = "Country";
                ddlCountries.DataBind();
                con.Close();
            }
        }
    }
}

[WebMethod]
public static object GetData(string country)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        string query = "SELECT * FROM Customers WHERE Country = @Country";
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.Connection = con;
            cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = country;
            con.Open();
            SqlDataReader sdr = cmd.ExecuteReader();
            if (sdr.Read())
            {
                return new { Name = sdr["Name"], Id = sdr["CustomerId"] };
            }
            con.Close();
        }

        return null;
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As SqlConnection = New SqlConnection(conString)
            Using cmd As SqlCommand = New SqlCommand("SELECT Country FROM Customers", con)
                con.Open()
                ddlCountries.DataSource = cmd.ExecuteReader()
                ddlCountries.DataTextField = "Country"
                ddlCountries.DataValueField = "Country"
                ddlCountries.DataBind()
                con.Close()
            End Using
        End Using
    End If
End Sub

<WebMethod>
Public Shared Function GetData(ByVal country As String) As Object
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Dim query As String = "SELECT * FROM Customers WHERE Country = @Country"
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.Connection = con
            cmd.Parameters.Add("@Country", SqlDbType.VarChar).Value = country
            con.Open()
            Dim sdr As SqlDataReader = cmd.ExecuteReader()

            If sdr.Read() Then
                Return New With {
                    .Name = sdr("Name"),
                    .ID = sdr("CustomerId")
                }
            End If
            con.Close()
        End Using

        Return Nothing
    End Using
End Function

Screenshot