Mega Code Archive

 
Categories / C# Tutorial / GUI Windows Forms
 

Fill data from Database to ListView

using System; using System.Data.SqlClient; using System.Data; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms;   public class DataReaderTest : System.Windows.Forms.Form   {     public DataReaderTest()     {       this.lvCustomers = new System.Windows.Forms.ListView();       this.SuspendLayout();       //        this.lvCustomers.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)          | System.Windows.Forms.AnchorStyles.Left)          | System.Windows.Forms.AnchorStyles.Right);       this.lvCustomers.Location = new System.Drawing.Point(8, 8);       this.lvCustomers.Name = "lvCustomers";       this.lvCustomers.Size = new System.Drawing.Size(276, 248);       this.lvCustomers.TabIndex = 0;       //        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);       this.ClientSize = new System.Drawing.Size(292, 266);       this.Controls.AddRange(new System.Windows.Forms.Control[] {this.lvCustomers});       this.Load += new System.EventHandler(this.DataReaderTest_Load);       this.ResumeLayout(false);     }     private System.Windows.Forms.ListView lvCustomers;     private string connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI";     private void DataReaderTest_Load(object sender, System.EventArgs e)     {       string SQL = "SELECT * FROM Customers";       lvCustomers.View = View.Details;       SqlConnection con = new SqlConnection(connectionString);       SqlCommand cmd = new SqlCommand(SQL, con);       SqlDataReader r = null;            con.Open();       r = cmd.ExecuteReader();       for (int i = 0; i <= r.FieldCount - 1; i++)       {         lvCustomers.Columns.Add("Column " + (i + 1).ToString(),100, HorizontalAlignment.Left);       }       while (r.Read())       {         ListViewItem lvItem = new ListViewItem(r[0].ToString());         for (int i = 1; i <= r.FieldCount - 1; i++)         {           lvItem.SubItems.Add(r[i].ToString());         }         lvCustomers.Items.Add(lvItem);       }       con.Close();     }     public static void Main()     {       Application.Run(new DataReaderTest());     }   }