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 DataGrid to an ArrayList of objects?

Here is a technique for binding an ArrayList of objects where the objects contain public properties that should appear as columns in the DataGrid. To bind an ArrayList of these objects to a DataGrid, add a custom DataGridTableStyle that has a MappingName of "ArrayList", and then use the each property name as the MappingName for each column.

For this sample, here is a class of name-value pairs with two public properties, Name and Value.

public class NameValuePair
{
  // ...

  public string Name
  {
    get { /* ... */  }
    set { /* ... */ }
  }

  public double Value
  {
    get { /* ... */ }
    set { /* ... */ }
  }
}

Here is a method that binds a DataGrid to an ArrayList of NameValuePair objects. This would be called when the Form is loaded.

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

// ...

private ArrayList arrayList1;
private DataGrid dataGrid1;

private void BindDataGridToArrayList()
{
  dataGrid1.DataSource = arrayList1;

  // create a custom table style
  DataGridTableStyle ts = new DataGridTableStyle();
  ts.MappingName = "ArrayList";

  // add a column style for the Name property
  DataGridTextBoxColumn cs1 = new DataGridTextBoxColumn();
  cs1.MappingName = "Name"; // public property name
  cs1.HeaderText = "Name";
  ts.GridColumnStyles.Add( cs1 );

  // add a column style for the Value property
  DataGridTextBoxColumn cs2 = new DataGridTextBoxColumn();
  cs2.MappingName = "Value"; // public property name
  cs2.HeaderText = "Value";
  cs2.Format = "f4";
  ts.GridColumnStyles.Add( cs2 );

  // add the custom table style
  dataGrid1.TableStyles.Clear();
  dataGrid1.TableStyles.Add( ts );
}

You can download a working project that also has code to delete rows and add new rows to the bound ArrayList.

George Shepherd, Syncfusion, and Stuart Celarier, Fern Creek



Page view counter