How to fill a Datagridview manually, after having used "Tolist()" from the link as Datasource?

Asked

Viewed 234 times

2

I am filling the Datasource of my Datagridview so:

var enderecos = from endereco in EnderecoBusiness.Enderecos
                                select new {
                                    Logradouro = endereco.Logradouro,
                                    Numero = endereco.Numero,
                                    Cidade = endereco.Cidade,
                                    Estado = endereco.Estado
                                };

dgvEndereco.DataSource = enderecos.ToList();

Where EnderecoBusiness.Enderecos returns me a list of type Endereco containing attributes filled by database data.

But if the user registers in the database another address I need to add a new line in this Datagridview.

I tried to do something like:

string[] novoEndereco = new string[4];

novoEndereco[0] = txtLogradouro.Text;
novoEndereco[1] = txtNumero.Text;
novoEndereco[2] = txtCidade.Text;
novoEndereco[3] = txtEstado.Text;

dgvEndereco.Rows.Add(novoEndereco);

But I get the error :

It is not possible to add lines programmatically to the Datagridview line collection when the control is associated with data

What is the best way to proceed ?

NOTE: I also need this new line to be added with some small icon in this first column that the image below is indicating with the arrow, just so that the user is aware of which line was added

inserir a descrição da imagem aqui

1 answer

1


Just redo the initial process, it will update the information of the dgv.

var enderecos = from endereco in EnderecoBusiness.Enderecos
                                select new {
                                    Logradouro = endereco.Logradouro,
                                    Numero = endereco.Numero,
                                    Cidade = endereco.Cidade,
                                    Estado = endereco.Estado
                                };

dgvEndereco.DataSource = enderecos.ToList();
  • 1

    I ended up creating a method that performs this every time a new data is added in the database, but every time I call this function and make a query in the database that returns several lines. I wouldn’t have a performance problem with that ?

  • 1

    Well you will have a processing cost to redo this list and then pass it to the dgvEndereco, but I believe it is the best way to do it... maybe it comes someone with a better answer! By the way don’t forget to give a Up and mark as answer if it helped you...

Browser other questions tagged

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