Datagridviewcomboboxcolumn loses selected value

Asked

Viewed 380 times

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 make the bind of my list perfectly. Below it I have the code to fill my combobox. After changing the focus of the datagridview line the combobox is null.

I wish I could define an index so that this combo does not come with the null value and that it does not lose the selection I chose. It is possible to do this ?

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);
  • How do I set an index? Already tried using listProducts.Selectedindex = 0 after binding to COMBOBOX?

1 answer

1

Friend, I do not know if I understand your question, but if I understand, in this case you should use Itemtemplate.

Follow 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 popular the dropdown at the moment it is creating 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;
    }

So item by item you populate whatever you want within Itemtemplate. It can be a Dropdown, it can be a Checkbox, anyway, whatever you want. And if you need to access any data key that is binding the line, use e.item.Dataitem;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.