Search code examples
c#datagridviewbindinglist

How do I map an array field to multiple columns in a WinForms DataGridView using a DataSource binding?


I have a class like this:

public class PricingRecord
{
    private string _name;
    private float[] _prices;

    public PricingRecord(string name, float[] prices)
    {
        _name = name;
        _prices = prices;
    }

    [DisplayName("Name")]
    public string PricingName => _name;

    public float[] Prices => _prices;
}

I want to map "Prices" to "Price 1", "Price 2", etc. columns in a DataGridView. I can get the columns to appear, but don't know how to make the mapping work.

Here's the main window:

public partial class MainForm : Form
{
    private int _numPricingColumns;
    private BindingList<PricingRecord> _records;

    public MainForm()
    {
        InitializeComponent();

        SetupPricingData();
        SetupGridView();
    }

    private void SetupPricingData()
    {
        _records = new BindingList<PricingRecord>();

        for (int i = 0; i < 100; i++)
        {
            var pricing = new PricingRecord($"Name {i + 1}", new [] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f });
            _records.Add(pricing);
        }

        _numPricingColumns = _records[0].Prices.Length;

        GridView.DataSource = _records;
    }

    private void SetupGridView()
    {
        //GridView.AutoGenerateColumns = false;

        //DataGridViewColumn column = new DataGridViewTextBoxColumn
        //{
        //    Name = "Name",
        //    DataPropertyName = "PricingName"
        //};
        //GridView.Columns.Add(column);

        for (int i = 0; i < _numPricingColumns; i++)
        {
            DataGridViewColumn column = new DataGridViewTextBoxColumn
            {
                Name = $"Price {i + 1}",
                DataPropertyName = $"Price{i + 1}"
            };
            GridView.Columns.Add(column);
        }
    }
}

If I don't use BindingView I can set it up all by hand, but then I have to maintain the rows and columns myself. I'd like to use BindingView but this doesn't seem to support mapping many columns to an array.


Solution

  • A faster and more flexible solution proved to be dropping BindingList and directly poking the cells in the grid. The need to map an array field to multiple columns becomes moot as it's done by hand.