Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

Fill ListBox with data from a DataReader

using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; public class ListBoxFillFromDataReader : System.Windows.Forms.Form {     private System.Data.SqlClient.SqlConnection connection;     private System.Data.DataSet dataSet;     private System.Data.SqlClient.SqlCommand command;     private System.Data.SqlClient.SqlDataAdapter dataAdapter;     private System.Windows.Forms.ListBox lbBugs;   private System.ComponentModel.Container components = null;   public ListBoxFillFromDataReader()   {     InitializeComponent();         string connectionString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";     using (connection = new System.Data.SqlClient.SqlConnection(connectionString))     {       connection.Open();       using(dataSet = new System.Data.DataSet())       {         dataSet.CaseSensitive=true;         string commandString = "Select ID, FirstName from Employee";         command = new System.Data.SqlClient.SqlCommand();         command.Connection=connection;         command.CommandText= commandString;         using (SqlDataReader dataReader = command.ExecuteReader())         {           while (dataReader.Read())           {             object bugID = dataReader["ID"];             object description = dataReader["FirstName"];             lbBugs.Items.Add(bugID.ToString() + ": " +  description.ToString());           }         }         }         }           }   protected override void Dispose( bool disposing )   {     if( disposing )     {       if (components != null)        {         components.Dispose();       }     }     base.Dispose( disposing );   }   private void InitializeComponent()   {         this.lbBugs = new System.Windows.Forms.ListBox();         this.SuspendLayout();         this.lbBugs.Location = new System.Drawing.Point(16, 8);         this.lbBugs.Name = "lbBugs";         this.lbBugs.Size = new System.Drawing.Size(216, 147);         this.lbBugs.TabIndex = 0;         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);         this.ClientSize = new System.Drawing.Size(264, 181);         this.Controls.AddRange(new System.Windows.Forms.Control[] {                                                                       this.lbBugs});         this.Name = "ListBoxFillFromDataReader";         this.Text = "ListBoxFillFromDataReader";         this.ResumeLayout(false);     }   [STAThread]   static void Main()    {     Application.Run(new ListBoxFillFromDataReader());   } }