How to get all selected values in a Datagridview?

Asked

Viewed 1,148 times

7

I’m trying to get all the selected values in one DataGridView and add to a IList<Object> but shows an exception. How to do this ?

I’m trying like this.

IList<Modulo> lista = gridModulos.SelectedRows.Cast<Modulo>().ToList();
  • How are these items selected? And what error message are you giving? Send me more details.

  • 2

    @Deramon solved the problem. I followed this example: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.databounditem%28v=vs.110%29.aspx

  • @Fernandopaiva You can add an answer with the solution(código) of your problem solved, it would help future users with the same problem.

2 answers

1

I think this might help

List<Modulo> lst = new List<Modulo>();

foreach (DataGridViewRow gridRow in dataGridView.Rows)
{
    Modulo modulo = new Modulo();

    foreach (DataGridViewCell gridCell in gridRow.Cells)
    {
        if (gridCell.Displayed == false)
        {
             continue;
        }

        // aqui tem acesso à linha (gridRow) e á coluna (gridCell.Value)
        // pode usar reflection para fazer set à propriedade dinamicamente.
        modulo.propriedade = gridCell.Value; 
    }

    lst.Add(modulo)
}

1

Hello, if you are feeding the dataGridView using the property datasource, you can use this code:

IList<Modulo> lista = gridModulos.SelectedRows.Cast<DataGridViewRow>().Select(p => (Modulo)p.DataBoundItem).ToList();

Browser other questions tagged

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