Reputation: 1264
I've got a datatable and one column is an integer ID foreign key to another database table.
I've got a datagridview and i'd like to use a combobox column to allow user to change value. But instead of using the integers, it would be great to use the names.
I've tried creating a simple struct with public members int ID and string Name; a dictionary and looked into enums (however values not known at compile time) but not got anything to work yet.
I was able to populate the combobox with struct values, but not able to programmatically set the selected item/index; ie, if ID "5" is in the datatable, set the combo box selected item to the struct that has an ID of 5.
So to be clear i'm wanting:
gridview datasource's fk ID's
1
2
3
Foreign Key table:
ID Name
1 Name 1
2 Name 2
3 Name 3
Datagridviewcombobox column should be loaded with three items; should display as "Name 1, Name 2, Name 3". Based on the gridview datasource's FK id, the selected item for each should match.
Upvotes: 4
Views: 17667
Reputation: 17049
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's 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);
Upvotes: 0
Reputation: 57823
You can set the DataGridViewComboBoxColumn.DataSource
property, and then use the ValueMember
and DisplayMember
properties to determine what is shown in the ComboBox
. Easiest is probably to load your FK values into DataTable
and use that as the 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 am not sure how you are binding your DataGridView
to your initial DataTable
, but you can associate the DataGridViewComboBox
column with a specific column in your original DataTable
using DataPropertyName
:
fkCol.DataPropertyName = "ColumnName";
Upvotes: 9