0
Hello, in a web application, I need to insert values in a list at different times. This insertion occurs after the user fills in fields on the page and gives the Submit in the form.
In Submit is called the method that inserts the values in the list.
In the method I have to instantiate the list to enter the values, but each time a new list is instantiated and I miss the previous one.
Follow the code I’m trying to formulate:
public static List<LanctoConferenciaCaixaModel> LanctoValorConferencia(string parDsFormaPagto, decimal parVlConferido)
{
List<LanctoConferenciaCaixaModel> listLancamentoCaixa = null;
if (listLancamentoCaixa == null)
{
listLancamentoCaixa = new List<LanctoConferenciaCaixaModel>();
}
listLancamentoCaixa.Add(new LanctoConferenciaCaixaModel()
{
dsFormaPgto = parDsFormaPagto,
vlConferido = parVlConferido
});
return listLancamentoCaixa;
}
I believe my problem is in the if testing if the list is null.
PS: I started with C# programming only 3 months ago. :)
You are declaring a null list and then immediately checking that it is null. So, always block
if
shall be executed, andlistLancamentoCaixa
will be a new list.– CypherPotato
list is attribute of some class? how do you use it outside of method?
– Rafa C.
@Cypherpotato, well observed, I copied the code from somewhere else and I didn’t notice it... but removing the null statement, in if it accuses "Use of local variable unassigned".
– Anderson Nuernberg
@Andersonnuernberg attributes an instance to it because then:
var listLancamentoCaixa = new List<LanctoConferenciaCaixaModel>();
– CypherPotato
@Cypherpotato, then I fall exactly into my initial question, every time I call the method, it instantiates a list, and I lose the values already entered. if is would be exactly to see if there was already an instance of the list and add new values.
– Anderson Nuernberg
need to move the variable declaration to another scope, in the class for example, otherwise it will create again always since the list is a local variable, which is lost when processing the page. Try to move it to the class scope, outside the method
– Ricardo Pontual
@Ricardopoint even moving out of the method, when testing if if is null, enters and creates a new instance, losing the values already informed.
– Anderson Nuernberg
this should happen pq every request is instantiated the page class again, you can solve this, just for this example (this is not the best way to do) declaring the variable as static
static List<LanctoConferenciaCaixaModel> listLancamentoCaixa = null;
. If you don’t know what a Static variable is, I suggest looking at the site– Ricardo Pontual
@Ricardopunctual, your tip to declare the variable as static worked in this case for what I need. Thank you.
– Anderson Nuernberg