List Box Data Binding in C# Windows Forms Application

How list box data binding works to bind list view and tree views with data from generic lists, arrays and other data sources.

By Tim Trott | C# ASP.Net MVC | September 8, 2008

Using data sets and SQL Server for list box data binding is all very well and good, but what if you don't have a database? You could add items from an array or list using a foreach loop, but luckily there is a better way.

.Net allows you to easily bind a list object to a list box control without the need to iterate through every item in the list. This method even works for custom types such as classes or structures.

In this example, I have created a custom Person structure that holds the first name and last name. I then set the data source of a list box to the instance of the Person object. When the program is run, the list box will contain "John" and "Jane". For advanced data types, you can set the property to be displayed using the DisplayMember property of the list box.

C#
public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
    Person[] People = new Person[] {
              new Person("John","Smith"),
              new Person("Jane" ,"Doe")};
    lstPersons.DataSource = People;
    lstPersons.DisplayMember = "FirstName";
  }
}


public struct Person
{
  private string firstName, lastName;
  
  public Person(string firstName, string lastName)
  {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  public string FirstName 
  { 
    get 
    { 
      return firstName; 
    } 
  }
  
  public string LastName 
  { 
    get 
    { 
      return lastName; 
    } 
  }
}

If you do not specify a DisplayMember it will use the value from the ToString() method (default will display "ListBoxBinding.Person", but you can override the ToString() method to provide data in the format you require.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 1 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. BE

    On Thursday 21st of April 2011, benjacomin said

    good! useful