Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

Binding ListBox to a Database table

using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; public class ListBoxBindingTable : System.Windows.Forms.Form {   private System.Windows.Forms.ListBox employeeList;   private System.ComponentModel.Container components = null;   public ListBoxBindingTable()   {     InitializeComponent();     string connectionString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";     string commandString = "Select ID, FirstName from Employee";     SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, connectionString);     DataSet dataSet = new DataSet();     dataAdapter.Fill(dataSet,"Employee");     DataTable dataTable = dataSet.Tables[0];     employeeList.DataSource= dataTable;     employeeList.DisplayMember = "Employee";   }   protected override void Dispose( bool disposing )   {     if( disposing )     {       if (components != null)        {         components.Dispose();       }     }     base.Dispose( disposing );   }   private void InitializeComponent()   {     this.employeeList = new System.Windows.Forms.ListBox();     this.SuspendLayout();     this.employeeList.Location = new System.Drawing.Point(8, 8);     this.employeeList.Name = "employeeList";     this.employeeList.Size = new System.Drawing.Size(272, 95);     this.employeeList.TabIndex = 0;     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);     this.ClientSize = new System.Drawing.Size(292, 133);     this.Controls.AddRange(new System.Windows.Forms.Control[] {this.employeeList});     this.Name = "ListBoxBindingTable";     this.Text = "ListBoxBindingTable";     this.ResumeLayout(false);   }   [STAThread]   static void Main()    {     Application.Run(new ListBoxBindingTable());   } }