Fills a ListBox with data from Database : ListBox « GUI Windows Forms « C# / CSharp Tutorial






using System;
using System.Windows.Forms;
using System.Data.SqlClient;

public class DataReaderTest : Form
{
    private ListBox lstNames;
    private string connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI";

  public DataReaderTest()
  {
    lstNames = new ListBox();
    lstNames.Dock = DockStyle.Fill;
    Controls.Add(lstNames);
    Load += new EventHandler(DataReaderTest_Load);
  }

  public static void Main()
  {
    DataReaderTest t = new DataReaderTest();
    Application.Run(t);
  }
    private void DataReaderTest_Load(object sender, System.EventArgs e)
    {
        string SQL = "SELECT ContactName FROM Customers";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(SQL, con);
        SqlDataReader r = null;
        con.Open();
        r = cmd.ExecuteReader();
        while (r.Read()) {
           lstNames.Items.Add(r["ContactName"]);
        }
        con.Close();
    }
}








23.27.ListBox
23.27.1.Set the TopIndex property of the ListBox to ensure the most recently added items are visibleSet the TopIndex property of the ListBox to ensure the most recently added items are visible
23.27.2.Add Items to ListBoxAdd Items to ListBox
23.27.3.Add ContextMenu to ListBoxAdd ContextMenu to ListBox
23.27.4.ListBox Items AddListBox Items Add
23.27.5.ListBox Items Add a RangeListBox Items Add a Range
23.27.6.ListBox Selection ModeListBox Selection Mode
23.27.7.Use RadioButton to control ListBox selection modeUse RadioButton to control ListBox selection mode
23.27.8.ListBox Events: SelectedIndexChanged, SelectedValueChanged, DataSourceChanged, DisplayMemberChanged, ValueMemberChanged
23.27.9.Add text in the TextBox to the ListBox
23.27.10.Fills a ListBox with data from Database