Data overlapping the onClick command

3

Well, I have a small problem with asp.net webforms . And I gave a cool pack.

I know the solution to this may be a bit simple, but I'm confused.

Follow the code:

public partial class Default : System.Web.UI.Page
{
    List<Pessoa> lista; 

    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) return;

        if (lista == null)
            lista = new List<Pessoa>();
    }

    protected void btnEnviar_Click(object sender, EventArgs e) {
        Pessoa p = new Pessoa();
        p.Id = lista.Count + 1;
        p.Nome = "João";
        p.Sobrenome = "Silva";
        p.Idade = 20;

        lista.Add(p);
        CarregarGrid();
    }

    private void CarregarGrid() {
        gvDados.DataSource = lista;
        gvDados.DataBind();
    }
}

When I click the button, I want to add a new person to the Grid, but it overrides, always on the pageload page the list is 'null'. It always adds:

1 - joao - silva.

How can I do this by keeping the current information? Whenever I click the button I want to always add one more, as an example below:

1 - joao - silva. 2 - joao - silva. 3 - joao - silva ....

    
asked by anonymous 28.10.2014 / 19:13

1 answer

4

You can solve this by using ViewState[] .

  

ViewState is the mechanism that ASP.NET uses to maintain the state of   controls, and objects when a Postback occurs on the page. At   information is stored in a html control of the hidden type called   _VIEWSTATE.

Font

Do as follows

    public List<Pessoa> lista  { 
        get { return ViewState["Pessoas"] as List<Pessoa>; } 
        set{ lista = value; } 
    }
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            ViewState["Pessoas"] = new List<Pessoa>();
            return;
        }
        if (lista == null) {
            lista = new List<Pessoa>();
        }
    }
    protected void btnEnviar_Click(object sender, EventArgs e) {
        Pessoa p = new Pessoa();
        p.Id = lista.Count + 1;
        p.Nome = "João";
        p.Sobrenome = "Silva";
        p.Idade = 20;

        lista.Add(p);
        CarregarGrid();
    }
    private void CarregarGrid() {
        gvDados.DataSource = lista;
        gvDados.DataBind();
    }
    
28.10.2014 / 20:25