Is there a function in Visual Studio where it is possible to fill a table with values of a List<>
without a certain number of positions?
Is there a function in Visual Studio where it is possible to fill a table with values of a List<>
without a certain number of positions?
What you need to do is use the LINQ feature to create a new anonymous type, and then populate the DataGridView with the anonymous type you created.
List<Usuario> lstUsr = preencheLstUsr();
var newList = lstUsr.Select(usuario => new
{
Id = usuario.id,
Nome = usuario.login,
LoginNome = usuario.login,
PerfilDescricao = usuario.perfil.descricao
}).ToList();
The method would look like this:
private void btnPreencheGrid_Click(object sender, EventArgs e)
{
List<Usuario> lstUsr = preencheLstUsr();
var novaListUsuario = lstUsr.Select(usuario => new
{
Id = usuario.id,
Nome = usuario.login,
LoginNome = usuario.login,
PerfilDescricao = usuario.perfil.descricao
}).ToList();
dgv.DataSource = null; //Limpa o grid;
dgv.DataSource = novaListUsuario;
dgv.Refresh();
}
For this change to work, you need to edit the DataGridView and change the DataSource to (none) in the editor, as well as edit each one of the columns that you understand.
That is, in each of the columns, change the DataPropertyName to match the name of the property in the anonymous type created with that popular pertende column.
This response is based on on that other , so I used as an example List<Usuario>
with those attributes% with%. But it's just an example that you can adapt to your reality.
You can assign a List directly to the DataSource of a GridView, but every time you modify your List you have to force a GridView update.
So instead I advise you to use a BindingList.
BindingSource bindingSource = new BindingSource();
BindingList<T> bindingList = new BindingList<T>(lista);
bindingSource.DataSource = bindingList;
gridView.DataSource = bindingSource;
Where list is its List<T>
, T
the type that the list enumerates and gridView
its GridView.
Once the Binding is done, you start to manipulate the bindingList
instead of its lista
, if you want to monitor any change in bindingList
you can implement the BindingList<T>.ListChanged
event.