DataGridViewComboBoxColumn loses selected value

3

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 row the combobox gets null.

I would like to be able to set an index so that this combo does not come with the null value and that it does not lose the selection that 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";

        dgvLotes.Columns.Add(comboBoxColumn);
    
asked by anonymous 28.07.2015 / 19:55

1 answer

1

Friend, I do not know if I understand your question, but if I understand, then you should use ItemTemplate.

Here is an example below:

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

In the code you will populate the dropdown as it is creating the rows 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 the item you populate whatever you want within the ItemTemplate. It can be a DropDown, it can be a CheckBox, anyway, whatever you want. And if you need to access any key of data that is binding on the line, use the e.Item.DataItem;

    
18.02.2016 / 16:38