Binding data into dropdownlist in ASP.Net using C#

Now I would like to create a dynamic dropdownlist in ASP.Net using C#. I have a dropdownlist and I want to display items in it by binding data from database into it on page load. My database is designed in MS SQL Server 2008, I have a table ( tblcountry ) and I want to get data from column "country" to display as items of dropdownlist in ASP.Net.


sample table
Sample  table 
Code design:
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

Code Behind :
Import two namespaces 
//import these two namespaces: System.Data and System.Data.SqlClient  to use  .NET 
//Framework Data Provider for SQL Server
using System.Data;
using System.Data.SqlClient;
    protected void Page_Load(object sender, EventArgs e)
    {

       if (!IsPostBack) {
          DataTable dt = new DataTable();
          dt = Loadlist();

          DropDownList1.DataSource = dt;
          DropDownList1.DataValueField = "country";
          //country is table field name in tblcountry
          DropDownList1.DataBind();
       }

    }

    public DataTable Loadlist()
    {
       SqlConnection con = new SqlConnection();
       string str;
       string sql;

       str="Server=UBEE_THAROTH ; Database=Drink;uid=sa;pwd=123;";
       sql = "Select * from tblcountry order by country asc";
                
                // connect to database
       con.ConnectionString = str;
       con.Open();
                
                //fill data into datatable
       SqlDataAdapter da = new SqlDataAdapter(sql,con);
       DataTable dt = new DataTable();
       da.Fill(dt);

       if(dt.Rows.Count>0){
           return dt;
       }
       else {
           return null;
       }           
   }


Done …..enjoy with it :) :)
Binding data into dropdownlist in ASP.Net using C# Binding data into dropdownlist in ASP.Net using C# Reviewed by BeiLover on 7:41 PM Rating: 5

2 comments:

Powered by Blogger.