Binding data into listbox from database in asp.net using c#

This post will guide you how to binding data into listbox from database (sql server) in asp.net using c# . I have a listbox and I want to generate its items by loading data from a table field when page load. I will load data from column "country" , which in table tblcountry in my database, into listbox2. 

In SQL Server:

Table Field: Table Name : tblcountry           
                Colum Name              Data Type
                 country_ID                 int
                 country                       varchar(50)

In ASP.Net : 

Code Design :    
<asp:ListBox ID="ListBox2" runat="server" AutoPostBack="false"> </asp:ListBox>

Code Behind :

// add namespace 
using System.Data;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)
{    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        // calling function loadlist 
        dt = Loadlist();


        ListBox2.DataSource = dt;   

        ListBox2.DataValueField = "country"
        //country is the name of table field
        ListBox2.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";


     con.ConnectionString = str;

     //open connection to SQL Server
     con.Open();  

   
     SqlDataAdapter da = new SqlDataAdapter(sql,con);
     DataTable dt = new DataTable();
     da.Fill(dt);   

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

      else {
           return null;
      }
}    



Done .... Hope this post is helpful for you :)
Binding data into listbox from database in asp.net using c# Binding data into listbox from database in asp.net using c# Reviewed by BeiLover on 11:20 AM Rating: 5

No comments:

Powered by Blogger.