Rob Hix
Rob Hix

Reputation: 37

DataGridView ComboBox Column with DataTableSource

I have been trying to figure this out for about a day now, and no luck. Hopefully someone here can help.

I have a DataTable object that is bound to my DataGridView. One column of the table, Col_4 in the example below needs to hold a value that comes from a enum type. In this case I have used colors. I need Col_4 of the table to be a column of ComboBox elements that allows me to select the desired color. The color selection will then be stored in the DataTable that is bound to the DataGridView.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        enum MyColors {Red, Green, Blue, Yellow, Orange, White};
        List<MyColors> colors = Enum.GetValues(typeof(MyColors)).Cast<MyColors>().ToList();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {                      
            DataTable table = new DataTable("theData");
            table.Columns.Add("Col_1");
            table.Columns.Add("Col_2");
            table.Columns.Add("Col_3");
            table.Columns.Add("Col_4");

            DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
            comboCol.ValueType = typeof(MyColors);
            comboCol.DataSource = colors;
            comboCol.DataPropertyName = "Col_4";

            DataRow row = table.NewRow();
            row["Col_1"] = 1;
            row["Col_2"] = 2;
            row["Col_3"] = 3;
            row["Col_4"] = 4;

            table.Rows.Add(row);

            dataGridView1.DataSource = table;
            dataGridView1.Columns.Add(comboCol);
            dataGridView1.AllowUserToAddRows = false;

            Console.WriteLine(dataGridView1.Rows[0].State.ToString());
        }

    }
}

I am having two problems with this:

  1. How do I get the column of ComboBox elements to have the "Col_4" header?
  2. How do I make the selected ComboBox value get correctly stored in the DataTable?

This may be simple, but I am new to C# and I am getting really confused.

Upvotes: 3

Views: 720

Answers (1)

Mehdi Haghshenas
Mehdi Haghshenas

Reputation: 2447

for your first problem just

comboCol.Header="Test";
comboCol.ValueMember="ColorId"; //that color id is the value of color class to be sorted in database 

For your second problem using the below code:

BindingSource bs=new BindingSource();
bs.DataSource=table;
datagridview1.DataSource=bs;

and when you want to save data in db

int columnvalueColorId=Convert.ToInt32((bs.current as DataRowView).Row["Col_4"].ToString());//if colum

Upvotes: 0

Related Questions