Binding DataGridView to DataTable but also including ComboBox as last column

Right now I have a DataGridView that is bound to a DataTable that works well and well. What I need to do in the DataGridView includes a new column at the very end, which is a ComboBox that will be dynamically loaded based on the key value of the row.

My columns are ID, Name and Count. The fourth column will be a ComboBox, which takes an ID and creates the values ​​in the dropdown based on that. I currently have a custom ComboBox that takes an ID in its constructor and populates it that way, but I couldn't figure out how this could be applied in the DataGridView. So, I made a copy of this custom ComboBox control and turned it into a DataGridViewComboBoxCell, but I still can't figure out how to dynamically bind it to the form. I scoured the internet and found some examples, but not exactly what I want to do.

This link shows what I want to do other than that I am using C # and not VB. Any ideas?

+2


source to share


3 answers


Here's what I just tried:

DataTable dt = new DataTable();
            dt.Columns.Add("Col");
            dt.Rows.Add();
            dt.Rows.Add();
            dt.Rows.Add();
            dt.Rows[0][0] = "1";
            dt.Rows[1][0] = "2";
            dt.Rows[2][0] = "3";
            dataGridView1.DataSource = dt;

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

            List<string> lstStr = new List<string>();
            lstStr.Add("1");
            lstStr.Add("2");
            lstStr.Add("3");
            lstStr.Add("4");

            ((DataGridViewComboBoxCell)(dataGridView1.Rows[0].Cells[1])).DataSource = lstStr;

      



Is this what you are looking for?

+3


source


Try the following:



// Create a new Combo Box Column

DataGridViewComboBoxColumn EmpIdColumn = new DataGridViewComboBoxColumn();

// Set the DataSource of EmpIdColumn as bellow

EmpIdColumn.DataSource = myDataSet.Tables[0];

// Set the ValueMember property as done bellow 

EmpIdColumn.ValueMember = myDataSet.Tables[0].Columns[0].ColumnName.ToString();

// Set the DisplayMember property as follow

EmpIdColumn.DisplayMember = EmpIdColumn.ValueMember;

      

+2


source


You can take or leave this path, but the way I was handling it (in VB) is to link the DGV to a collection of objects that contains additional members above and above my actual linked data. I use these additional elements as placeholders for additional materials.

I populate items from a data source (DB in my case) into a collection, populate the rest of the items as I need, and then bind the collection to the DGV. Since the additional members are not members of the original table, I can change their content. Then I don't have to deal with the "partial binding" of the control as you want.

Anyway, another way to dump the cat.

0


source







All Articles