Column ComboBox DataGridView with DataTableSource

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

I have a DataTable object bound to my DataGridView. One column of the Col_4 table in the example below should contain a value that comes from an enumeration type. In this case, I used colors. I need Col_4 of the table to be a column of ComboBox items that allows me to select the color I want. Then the color selection will be saved in the DataTable, which 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:

  • How do I get a column of ComboBox items for the "Col_4" header?
  • How do I make the correctly selected ComboBox value stored correctly in the DataTable?

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

+3


source to share


1 answer


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 use the below code:



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

      

and when you want to store data in db

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

      

0


source







All Articles