get the values of a generic list List<t>

Asked

Viewed 86 times

2

My project Winforms C# has a form with a GridControl(gvDados) and a button Sue with an event Click(). Validation takes place in the event Click from the process button, through a method responsible for returning true if there is a selected and false item if not and later, each item is stored in a generic list.

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 as follows: how can I also get all saved items in the list itensSelecionados at the event click() of the process button? I thought I’d do it this way:

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

And I’m getting the following mistake: System.NullReferenceException

  • You are probably experiencing this error because the list is not initialized.

  • 1

    within its function vc is re-declaring the List<string> itensSelected = new List<string>(); this makes it local scope Pata make it global scope switch by itensSelected = new List<string>();

  • That’s right Mark, it worked after fixing. Thank you very much :)

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 itensSelected within the scope of the function Returnee(), exactly like the object itensSelected defined in the scope of the form.

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

Change
List<string> itensSelecionados = new List<string>();
by only
itensSelecionados = new List<string>();
to solve

  • Perfect, that’s right! Thank you very much Umberto!

Browser other questions tagged

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