How do I get all the selected values in a DataGridView?

6

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

I'm trying like this.

IList<Modulo> lista = gridModulos.SelectedRows.Cast<Modulo>().ToList();
    
asked by anonymous 10.03.2016 / 18:49

2 answers

0

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)
}
    
15.06.2016 / 01:46
0

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();
    
27.07.2018 / 21:16