c# – DataGridViewComboBoxColumn loses selected value


I have a DataGridView and bind it through a list. So far so good…

Now I want to add a combobox (DataGridViewComboBoxColumn) dynamically based on another list.

In the first line of code I bind my list perfectly. Below it I have the code to fill my combobox. After changing the focus of the datagridview line, the combobox has a null value.

I would like to be able to define an index so that this combo doesn't come with a null value and that it doesn't lose the selection I chose. Is it possible to do that ?

dgvLotes.DataSource = lotesDB.GetLotesByStatus(ValorRadioSelecionado());

List<Produto> listProdutos = new List<Produto>();
        listProdutos.Add(new Produto(){Id = 1, Nome = "Produto 1"});
        listProdutos.Add(new Produto() { Id = 2, Nome = "Produto 2" });
        listProdutos.Add(new Produto() { Id = 3, Nome = "Produto 3" });
        listProdutos.Add(new Produto() { Id = 4, Nome = "Produto 4" });

        DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();
        comboBoxColumn.DataSource = listProdutos.ToList();
        comboBoxColumn.DataPropertyName = "Id";
        comboBoxColumn.ValueMember = "Id";
        comboBoxColumn.DisplayMember = "Nome";



Friend, I don't know if I understand your question, but if I understand, in that case you should use the ItemTemplate.

Below is an example:

<div class="row">
    <asp:DataGrid ID="datagrid" runat="server"  OnItemDataBound="datagrid_ItemDataBound" >
                    <asp:DropDownList runat="server" ID="dropdown">

In the code, you will populate the dropdown when it creates the lines in the ItemDataBound event:

  protected void datagrid_ItemDataBound(object sender, DataGridItemEventArgs e)
        //encontra o dropdown 
        DropDownList itemDropDown = (DropDownList)e.Item.FindControl("dropdown");

        //popular o dropdown list com seus valores

        //caso precise de acessar algum dado que já esteja no datagrid em alguma coluna.
        var dataitem = e.Item.DataItem;

Then item by item you populate whatever you want inside the ItemTemplate. It can be a DropDown, it can be a CheckBox, whatever you want. And if you need to access any data key that is binding on the line, use e.Item.DataItem;

Scroll to Top