get the values from a Listt generic list

2

My Winforms C # project has a form with a GridControl(gvDados) component and a Process button with a Click event . The validation happens in the Click event of the process button, through a method responsible for returning true if there is a selected item and false if not later, that each item is stored in a generic list. p>

List<string> itensSelecionados;
.
.
.
public bool RetornaSelecionado(bool Selecionado)
{
  List<string> itensSelecionados = new List<string>();

  foreach (int i in gvDados.GetSelectedRows())
  {
    DataRow row = gvDados.GetDataRow(i);       
    itensSelecionados.Add(row[0].ToString());
    //MessageBox.Show(row[0].ToString());
  }
  if(linhas > 0)
  {
    MessageBox.Show("Selecionou " + itensSelecionados.Count()+ " Itens.");
    return Selecionado = true;
  }
  else
  {
    MessageBox.Show("Não selecionou");
    return Selecionado = false;
  }
}

My question is this: how can I also get all items saved in the itensSelecionados list in the click () event of the render button? I thought of doing it this way:

  foreach (var i in itensSelecionados)
  {
    MessageBox.Show(i);
  }

And I'm getting the following error: System.NullReferenceException

    
asked by anonymous 26.09.2018 / 19:10

1 answer

6
  

And I'm getting the following error: System.NullReferenceException

In this code snippet List<string> itensSelecionados = new List<string>(); , you are defining a new object called SelectedStats within the scope of the ReturnSelected () function, exactly the same as the defined in the scope of the form.

Because of this, the this.itensSelected object, even after the ReturnSelected () function is still not initialized.

Swap List<string> itensSelecionados = new List<string>();
for only
itensSelecionados = new List<string>();
to solve

    
26.09.2018 / 19:37