Web Design that taps into the haromny and vision of your dreams.

List Box Data Binding in C# Windows Forms Application

List box data binding the easy way

Written By on in C#

221 words, estimated reading time 2 minutes.

Using datasets 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.

Windows Forms Applications Series
  1. Basics of C# Windows Forms Applications
  2. Menus, Popups and Toolbars in .Net Forms and C#
  3. Using Common Dialogue Boxes in C#
  4. List Boxes and Tree Views in C#
  5. List Box Data Binding in C# Windows Forms Application
  6. Using Multiple Forms in C# Applications with MDI
  7. Creating Controls for Windows Forms and C#
  8. Saving User Preferences and Settings within your C# Application

.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 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.

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 a format you require.

Last updated on: Thursday 22nd June 2017

 

Comments
benjacomin

benjacomin

good! useful

Reply to benjacomin

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me