Bind DataBase Values To DropDownList in Asp.Net C#

Bind DataBase Values To DropDownList


If Want To  List Items Display  Bind To DropdownList And Select Particular Data Usin Asp.Net C#.


                                DEMO




HTML CODING

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <form id="form1" runat="server">
          
 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="BIND " />
    
  <asp:Label ID="Label1" runat="server" ForeColor="#CC3300" Text="Country"></asp:Label>

<asp:DropDownList ID="ddlCountry" runat="server">

            </asp:DropDownList>

    </form>
</body>
</html>

C# CODING

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;

public partial class BindDropDown : System.Web.UI.Page
{
     
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbcon"].ToString());
        con.Open();

        SqlCommand cmd = new SqlCommand("select country from country", con);

        SqlDataReader rd=cmd.ExecuteReader();

        ddlCountry.Items.Clear();

        ddlCountry.Items.Add("Select Country");

        while(rd.Read())
        {

        ddlCountry.Items.Add(rd[0].ToString());

        }              

    }
}


First Add - New - Web Form - Select Label  & button & DropDownList From ToolBox






Next - Insert The DataBase Field Values 







Next - Add NameSpaces  & DataBase Connection - Select Field Name & Clear DropDownList Items Before Condition Check for Avoid Duplicate Values Entered 







Next - Run [F5] Run The Program  - Bind Button Click - Bind Values To DropDownList.








0 comments:

Post a Comment