C # datagridview combo list of column data source from list / dictionary / datatable

I have a data table, and one column is the foreign key of an integer identifier for another database table.

I have a data grid, and I would like to use a combo column to allow the user to change the value. But instead of using integers, it would be great to use names.

I tried to create a simple structure with public members int ID and string Name; The dictionary also looked into the enumerations (however, the values ​​are not known at compile time), but have not yet received anything to work.

I was able to populate the combo box with structure values, but could not programmatically set the selected item / index; those. if identifier "5" is in the data table, set the structure that has identifier 5 for the selected element of the combined field.

So, to be clear, I want:

gridview datasource fk ID 1 2 3 Foreign Key table: ID Name 1 Name 1 2 Name 2 3 Name 3 

The Datagridviewcombobox column must be loaded with three elements; should appear as "Name 1, Name 2, Name 3". Based on the FK identifier of the gridview data source, the selected item for each must match.

+4
source share
2 answers

You can set the DataGridViewComboBoxColumn.DataSource property, and then use ValueMember and DisplayMember to determine what is shown in the ComboBox . The easiest way is probably to load the FK values ​​into a DataTable and use this as a data source. For your example:

 // assuming your DataGridViewComboBox column is fkCol // and your fk values are in a DataTable called fkTable fkCol.DataSource = fkTable; fkCol.ValueMember = "ID"; fkCol.DisplayMember = "Name"; 

I'm not sure how you bind your DataGridView to your original DataTable , but you can bind the DataGridViewComboBox column to a specific column in the original DataTable using DataPropertyName :

 fkCol.DataPropertyName = "ColumnName"; 
+9
source
  DataAccessLayer dal = new DataAccessLayer(); DataTable movies = dal.GetMovies(); gvMovies.DataSource = movies; gvMovies.AllowUserToAddRows = false; gvMovies.AllowUserToDeleteRows = false; //Create the new combobox column and set it DataSource to a DataTable DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn(); col.DataSource = dal.GetMovieTypes(); ; col.ValueMember = "MovieTypeID"; col.DisplayMember = "MovieType"; col.DataPropertyName = "MovieTypeID"; //Add your new combobox column to the gridview gvMovies.Columns.Add(col); 
0
source

All Articles