How can I allow insertion directly into a DataGridView?

0

I'm setting DataSource of a DataGridView to List<T> . I enabled by the designer "enable addition".

But that line is not appearing with an asterisk to add new elements.

My code looks 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;
}
    
asked by anonymous 24.12.2013 / 19:51

1 answer

0

The problem is that you are trying to put List<T> into DataSource , however a list does not have the capabilities to connect the screen component to the property.

Instead of using a List<T> use a BindingList<T> . This type provides two-way binding , that is, what you add by 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 IBindingList interface that contains the AllowNew property. This property will be false when there is no default constructor for T .

As the example:

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

When the constructor is empty or omitted (there are no others) 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" },
};

However,ifyourclassdoesnothaveadefaultconstructor:

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

IfyouneedtouseList<T>,youcancreateBindingList<T>fromthelist,startapropertyofyourformwith:

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.

    
24.12.2013 / 19:51