3
Guys, I have a little problem in Asp.net webforms. And I made a nice pie.
I know the solution to this might be a little simple, but I’m confused.
Follows 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 on the button, I want to add a new person in the Grid, but it is overwritten, always in the pageload of the page the list is as 'null'. Always he adds:
1 - Joao - silva.
How can I do this keeping the information current? Whenever you click on the button I want you to always add one more, as an example below:
1 - Joao - silva. 2 - Joao - silva. 3 - John - John....
I don’t quite understand your question. When Gridview is loaded it displays the correct data, but when you click add it loads all the data? I think for your case it might be best to iterate over the list and add one to one. If your problem is with regard to loss of user provided data.
– Richard Dias
@Richarddias Um, right, so the problem is that when I click the button, the page of the 'Reload', and with that I lose the information from the list. That is, it will always be a new one. The first time I click, Gridview displays the data correctly, but it ALWAYS displays the first data.
– Erico Souza
Have you used debug mode to see if your list is being filled in correctly? I think to accomplish this action maybe you could use ajax, avoid reloading the whole page. I don’t use Web Forms, but I know a little bit about Windows Forms and MVC, so I don’t really know what the implications of that might be.
– Richard Dias
Right, I will perform the test with ajax, I think that really the problem is in the page Reload that it loses the information. I’ve used debug, and the list is filled in correctly yes.
– Erico Souza
Unless he stores the list in a session. Here’s what’s best for his case.
– Richard Dias
@Tiagosilva thanks for the tip from Viewstate. :)
– Erico Souza