Create a web application to display Databinding using dropdownlist control

First Step:- Working with Database

Then Follow  ;-

 Default.aspx 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 

Inherits="Database.Default" %> 

<!DOCTYPE html> 

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

<head runat="server"> 

    <title></title> 

</head> 

<body> 

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

        <div> 

            <asp:DropDownList ID="DropDownList1" runat="server" 

DataSourceID="SqlDataSource1" DataTextField="City" DataValueField="City"> 

            </asp:DropDownList> 

            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ 

ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM 

[Customer]"></asp:SqlDataSource> 

        </div> 

        <p> 

            <asp:Button ID="Button1" runat="server" Height="31px" Text="Click Me !" 

OnClick="Button1_Click" /> 

        </p> 

        <p> 

            <asp:Label ID="Label1" runat="server" Text=" "></asp:Label> 

        </p> 

    </form> 

</body> 

</html> 

Default.aspx.cs 

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Web; 

using System.Web.UI; 

using System.Web.UI.WebControls; 

using System.Data; 

using System.Data.SqlClient; 

using System.Configuration; 

 

namespace Database 

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

    { 

        protected void Page_Load(object sender, EventArgs e) 

        { 

            if (IsPostBack == false) 

            { 

                string connStr = 

                ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 

                SqlConnection con = new SqlConnection(connStr); 

                SqlCommand cmd = new SqlCommand("Select Distinct City from Customer", con);

                con.Open();  

                SqlDataReader reader = cmd.ExecuteReader(); 

                DropDownList1.DataTextField = "City"; 

                DropDownList1.DataBind(); 

                reader.Close();                 

                con.Close(); 

            } 

        } 

        protected void Button1_Click(object sender, EventArgs e) 

        { 

            Label1.Text = "The City You have Selected is : " + DropDownList1.Text; 

        } 

    } } 

Output:-



Post a Comment

0 Comments