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 TrottC# ASP.Net MVC • September 8, 2008
List Box Data Binding in C# Windows Forms Application

Using data sets and SQL Server for list box data binding is all very 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 iterating through every item in the list. This method even works for custom types such as classes or structures.

In this example, I created a custom Person structure with the first and last names. 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.

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. 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 only 1 comment. Why not join the discussion!

New comments for this post are currently closed.