简体   繁体   中英

DataGridView Convert TextBoxColumn to ComboBoxColumn

I have a simple database(SQL) the Cars Table has six fields: ID, owners, year, color, make and model. The Colors Table is just: ID, ColorName.

I have a Form with a DataGridView. When I bind my Cars table to the DataGridView everything works to this point.

Now, I am trying to make the Colors Column in the DataGridView to be a comboBox for editing and list only colors from my Colors Table. I can make and add a comboBox to the DataGridView but I would like to just 'convert' the Column that already has data in it.

Thanks in advance for any help offered.

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace EditingCells
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var myDataBase = new CarsEntities();
            List<MyCar> data = myDataBase.MyCars.OrderBy(o => o.Owner).ToList();

            //dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = data;

            const int index = 2; // Column Index for Color

            List<string> myColor = myDataBase.Colors.Select(s => s.Color1).ToList();

            var comboBoxColumn = new DataGridViewComboBoxColumn
            {
                DataSource = myColor,
                DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing,
                AutoComplete = true,
            };
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].EditType.ToString());
        }
    }
}

Based on this -> " Change Cell Type on Databound DataGridView to Custom DataGridViewCell Type " topic, I suggest you work on something like the following:

public partial class Form1 : Form
{
    List<string> availableCarColors = new List<string>();
    List<MyCar> data = new List<MyCar>();

    public Form1()
    {
        InitializeComponent();

        availableCarColors.Add("Red");
        availableCarColors.Add("Blue");

        data.Add(new MyCar("Lexus", "Blue"));
        data.Add(new MyCar("BMW", "Red"));

        DataGridViewTextBoxColumn colModel = new DataGridViewTextBoxColumn();
        colModel.Name = "Model";                //Header Text
        colModel.DataPropertyName = "Model";    //Property Name of my car class

        DataGridViewComboBoxColumn colColor = new DataGridViewComboBoxColumn();
        colColor.Name = "Color";
        colColor.DataPropertyName = "Color";
        colColor.DataSource = availableCarColors;

        dataGridView1.AutoGenerateColumns = false;
        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {colModel, colColor});
        dataGridView1.DataSource = data;
    }

    class MyCar
    {
        public string Model { get; set; }
        public string Color { get; set; }

        public MyCar(string model, string color)
        {
            Model = model;
            Color = color;
        }
    }
}

You must populate your DataGridViewComboBoxColumn with Colors table data using this setting:

I just wanted to post how I used @Tezzo's Solution to get the results I needed:

using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace EditingCells
{
    public partial class Form1 : Form
    {
        private readonly CarsEntities _myDataBase = new CarsEntities();

        public Form1()
        {
            InitializeComponent();

            List<MyCar> myData = _myDataBase.MyCars.ToList();

            // Yes, you have do make Columns manually.
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = myData;

            List<Color> myColors = _myDataBase.Colors.ToList();

            var carOwner = new DataGridViewTextBoxColumn
                {
                    DataPropertyName = "Owner",
                    HeaderText = @"Owner",
                    Name = "Owner",
                };
            dataGridView1.Columns.Add(carOwner);

            var carColor = new DataGridViewComboBoxColumn
                {
                    // Field Name where existing data is stored
                    DataPropertyName = "CarColor",
                    HeaderText = @"Color",
                    Name = "Color",
                    DataSource = myColors,
                    DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing,
                    AutoComplete = true,

                    // Field value from DataSource to store in Car.Color field
                    ValueMember = "ColorName",

                    // Field value from DataSource to show in DataGridView Column
                    DisplayMember = "ColorName",
                };
            dataGridView1.Columns.Add(carColor);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _myDataBase.SaveChanges();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM