Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I bind a control to an ArrayList so that changes are shown correctly?

I am binding a ListBox to an ArrayList. The initial display is okay, but changes to the ArrayList are not shown in the ListBox. How can I get the changes to show properly?

In an ArrayList, the "plumbing" is not available to support two-way binding as with a DataSet. So you have to handle the synchronization yourself. Here is a fragment that binds a ListBox to an ArrayList.

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

public class Form1 : Form
{
  private ListBox listBox1;
  private ArrayList colors;

  // ...

  public Form1()
  {
    InitializeComponent();
    colors = new ArrayList( new string[]  { "red", "green", "blue"  } );
    listBox1.DataSource = colors;
  }
}

One way to synchronize changes in the bound data object to the ListBox is to use the CurrencyManager from the System.Windows.Forms namespace as shown here.

private void button1_Click( object sender, System.EventArgs e )
{
  // change the bound data object
  colors.Add( "lavender" );

  // use currency manger to synch up listBox1
  BindingManagerBase bm = listBox1.BindingContext[ colors ];
  CurrencyManager cm = (CurrencyManager) bm;
  if ( cm != null ) cm.Refresh();
}

Another way to do this is to set the ListBox's DataSource to null and then reset it to the ArrayList as shown here.

private void button2_Click(object sender, System.EventArgs e)
{
  // change the bound data object
  colors.Add( "mauve" );

  // reset the DataSource to synch up listBox1
  listBox1.DataSource = null;
  listBox1.DataSource = colors;
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter