Bind DropDownList With SQL Database In ASP.NET Web Forms | Learn ASP.NET

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Configuration;

using System.Data;


namespace PopulateDataInDropDown

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                BindDropDownList();

            }

        }


        void BindDropDownList()

        {

            SqlConnection con = new SqlConnection(cs);

            string query = "select * from employee";

            SqlDataAdapter sda = new SqlDataAdapter(query,con);

            DataTable data = new DataTable();

            sda.Fill(data);

            DropDownList1.DataSource = data;

            DropDownList1.DataTextField = "name";

            DropDownList1.DataValueField = "id";

            DropDownList1.DataBind();


            ListItem SelectItem = new ListItem("Select Employee","-1");

            SelectItem.Selected = true;

            DropDownList1.Items.Insert(0,SelectItem);

        }


        protected void Button1_Click(object sender, EventArgs e)

        {

            if (DropDownList1.SelectedValue == "-1")

            {

                Response.Write("Please select an employee");

            }

            else

            {

                Response.Write("Selected Item Text is : " + DropDownList1.SelectedItem.Text + "<br>");

                Response.Write("Selected Item Value is : " + DropDownList1.SelectedItem.Value + "<br>");

                Response.Write("Selected Item Index is : " + DropDownList1.SelectedIndex + "<br>");

            }

        }

    }

}

Above File is PopulateDataInDropDown\WebForm1.aspx.cs





<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PopulateDataInDropDown.WebForm1" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

        <asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width="186px">

        </asp:DropDownList>

        <div>

            <br />

            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />

        </div>

    </form>

</body>

</html>

Above File is PopulateDataInDropDown\WebForm1.aspx














Comments

Popular posts from this blog

AJAX Method Of jQuery AJAX In ASP.NET Web Forms | Learn ASP.NET Web Forms

List Box In ASP.NET Web Forms | ASP.NET ListBox | Web Forms Tutorial | ASP.NET

Display Auto Increment Value In Text Field After Insert To Database ASP.NET