Live Chat Icon For mobile
Live Chat Icon

How can I bind an ArrayList to a DataGrid

Platform: WinForms| Category: Data Binding

Here is a technique for binding an arraylist of objects where the objects contain public property that can appear as columns in the datagrid. In this example, the object contains 2 public doubles, one named value and the other named sqrt. To bind this arraylist to a datagrid, add a custom tablestyle that has a MappingName of ”ArrayList”, and then use the property names as the MappingName for each column. Below are some code snippets. You can download a working project that also has code to delete rows and add new rows to the bound arraylist.

private void Form1_Load(object sender, System.EventArgs e)
    {
      CreateArrayList();
      BindArrayListToGrid();
    }

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

      //create a custom tablestyle and add two columnstyles
      DataGridTableStyle ts = new DataGridTableStyle();
      ts.MappingName = ''ArrayList'';

      int colwidth = (dataGrid1.ClientSize.Width - ts.RowHeaderWidth - SystemInformation.VerticalScrollBarWidth - 5) / 2;

      //create a column for the value property
      DataGridTextBoxColumn cs = new DataGridTextBoxColumn();
      cs.MappingName = ''value''; //public property name
      cs.HeaderText = ''Random Number'';
      cs.Format = ''f4'';
      cs.Width = colwidth;
      ts.GridColumnStyles.Add(cs);

      //create a column for the sqrt property
      cs = new DataGridTextBoxColumn();
      cs.MappingName = ''sqrt'';  //public property name
      cs.HeaderText = ''Square Root'';
      cs.Format = ''f4'';
      cs.Width = colwidth;
      ts.GridColumnStyles.Add(cs);

      dataGrid1.TableStyles.Clear();
      dataGrid1.TableStyles.Add(ts);
    }

    private void CreateArrayList()
    {
      arrayList1 = new ArrayList();

      //add some items
      Random r = new Random();
      for (int i = 0; i < 20; ++i)
        arrayList1.Add(new RandomNumber(r.NextDouble()));

    }

    //create a struct or class that defines what you want in each row
    //the different columns in the row must be public properties
    public struct RandomNumber
    {
      private double number;

      public RandomNumber(double d)
      {
        number = d;
      }

      public double value 
      {
        get{ return number; }
        set{ number = value;}
      }

      public double sqrt
      {
        get {return Math.Sqrt(this.value);}
      }
    }

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.