I work in a Windows Forms app in which I have a DataGridView control in which one of its columns is of type Combobox, I can populate the ComboBox with data without any problem.
The problem I have is that I need the first element that contains the Combobox to be selected, in this case <<Seleccione>>
I have not been able to get it at first sight, nothing is seen in the ComboBox until I click to be able to display the ComboBox and be able to select the items .
This way I load the ComboBox
public IEnumerable<UniversalExtend> SelectList(Expression<Func<UnidadMedida, UniversalExtend>> source)
{
return _unidadMedidaRepository.SelectList(source);
}
public IEnumerable<UniversalExtend> ListaUnidadMedidas
(Expression<Func<UnidadMedida, UniversalExtend>> source)
{
var listaItem = SelectList(source).ToList();
listaItem.Insert(0, new UniversalExtend() { Id = -1, Descripcion = "<<<Seleccione>>>" });
return listaItem;
}
Persistence
public IEnumerable<UniversalExtend> SelectList(Expression<Func<T, UniversalExtend>> source)
{
using (var context = new BusinessContext())
{
var result = context.Set<T>().AsNoTracking()
.Select(source).ToList();
return result;
}
}
Binding the data to the ComboBox
dataGridView1.AutoGenerateColumns = false;
DataGridViewComboBoxColumn cboColMedida = dataGridView1.Columns["colCombo"] as DataGridViewComboBoxColumn;
cboColMedida.DataSource =
_saUnidadMedida.ListaUnidadMedidas(
x => new UniversalExtend() {Id = x.UnidadMedidaId, Descripcion = x.Abreviacion}).ToList();
cboColMedida.DisplayMember = "Descripcion";
cboColMedida.ValueMember = "Id";
This is how it is shown when the cbo is already loaded with data.
I've been playing with your code and the answer is quite simple just assign a value to the combobox cell (In your example give it the value -1 that you declared in the Id) right after binding the data with your combobox.
In other words, in the part of the code where you assign the DataSource it would look like this:
And the function that will make the selection every time a new row is added would be:
I hope you can solve the problem.
All the best
What you need is to capture the default null value of the column in the combobox:
This after having finished filling the data to the DataGridViewComboBoxColumn