How can I allow insertion directly into a Datagridview?

Asked

Viewed 887 times

0

I am setting the DataSource of a DataGridView with a List<T>. I enabled by designer "enable addition".

But there is not appearing that line with asterisk for adding new elements.

My code is like this:

public IEnumerable<Valor> Valores
{
    get;
    set;
}

private void Form1_Load(object sender, EventArgs ev)
{
    if (Valores == null)
    {
        Valores = new List<Valor>();
    }

    dataGrid.DataSource = Valores;
}

1 answer

0


The problem is you’re trying to put a List<T> in the DataSource, however a list does not have the resources to connect the screen component with the property.

Instead of using a List<T> use a BindingList<T>. This type provides two-way Binding, that is, what you add through the grid will be added to the object, and what is added to the object will be added to the grid.

BindingList<T> implements the interface IBindingList containing the property AllowNew. This property will be false when there is no default constructor for T.

As an example:

public class Pessoa
{
    public string Nome { get; set; }
    public int Idade { get; set; }
}

When the constructor is empty or omitted (with no other) it means that you have a default constructor. In this case your grid will show the field to insert a new element.

public BindingList<Pessoa> lista = new BindingList<Pessoa>
{
    new Pessoa { Idade = 20, Nome = "Teste 1" },
    new Pessoa { Idade = 22, Nome = "Teste 2" },
    new Pessoa { Idade = 23, Nome = "Teste 3" },
};

pode adicionar

However, if your class does not have a standard constructor:

public class Pessoa
{
    public string Nome { get; set; }
    public int Idade { get; set; }
    public Pessoa(int x) { }
}

não pode adicionar


If you need to use a List<T>, you can create a BindingList<T> from the list, start a property of your form with:

ListaBinding = new BindingList<Pessoa>( new List<Pessoa>() );

Use this list to work with the grid and then you can pass the data you want to your other list.

Browser other questions tagged

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