inspiration
inspiration

Reputation: 174

DataGridView C# Add Different Values Into a Combobox for each row using MVP Pattern

I am currently trying to add values from a list of Layer(my class) objects to a datagridview.The first column is just a regular cell with text, but I want the second column to include comboboxes with values for each row. I have a foreach loop in my presenter that loops through the list of objects and calls the method AddRow, passing it the name value and the styles list. This is what I got so far. The list of titles are being brought in fine, but the styles are not there for the comboboxes. How can I populate a combobox with the values inside of the list for each row that is created? Due to company policy I can't post a screenshot so I'll do my best to answer any ambiguities, thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Service
{
    public class Layer
    {
        public string Name { get; set; }
        public string Title { get; set; }
        public string Abstract { get; set; }
        public bool Selected { get; set; }
        public List<string> CRS = new List<string>();
        public List<string> Styles = new List<string>();

    }
}

//

 //Method Inside of presenter to provide datagridview with values
 public void ProvideLayers()
        {
            if (_lview != null && _layers != null)
            {

                foreach (Layer lay in _layers)
                {
                    if (lay.Styles.Count == 0)
                    {
                        _lview.AddRow(lay.Title,new List<string>());
                        continue;
                    }
                    else
                    {
                        _lview.AddRow(lay.Title,lay.Styles);
                    }

                }

            }

        }

//

public void AddRow(string lName,List<string> lStyles)
        {
            dataGridView1.Rows.Add(lName,lStyles);
        }

Upvotes: 0

Views: 4749

Answers (1)

Neil Smith
Neil Smith

Reputation: 2565

You can set the combo box's data source.

public void AddRow(string lName,List<string> lStyles)
{
    var dgvRow = new DataGridViewRow();

    dgvRow.Cells.Add(new DataGridViewTextBoxCell());
    dgvRow.Cells.Add(new DataGridViewComboBoxCell());

    dgvRow.Cells[0].Value = lName;

    ((DataGridViewComboBoxCell) dgvRow.Cells[1]).DataSource = lStyles;

    dataGridView1.Rows.Add(dgvRow);
}

Note: If you're not setting up your columns already, doing this will force you to define the DataGridView's columns like so:

dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
dataGridView1.Columns.Add(new DataGridViewComboBoxColumn());

More info here about ComboBox.DataSource

Upvotes: 2

Related Questions