b1sh0p b1sh0p - 1 year ago 179
ASP.NET (C#) Question

Adding objects to array on button click

I have a "person" class with a constructor that looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Programming_handin_2___Arrays
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Password { get; set; }

public Person(string name, int age, string password)
{
this.Name = name;
this.Age = age;
this.Password = password;
}

public override string ToString()
{
return Name + ", " + Age + ", " + Password;
}
}
}


I also have an aspx page with a few Textboxes, to add the variables above.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name:<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
Age:<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
Password:<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add person" />
<br />
<br />
</div>
</form>
</body>
</html>


My goal is to create a new "person" every time someone fills out the form and clicks the button. The "person" should then be displayed on the page. What is the best way to achieve this?

Answer Source
List<Person> persons;
 protected void Page_Load(object sender, EventArgs e){

  if(!IsPostBack){
     List<Person> persons= new List<Person>();
     Session["personslist"]=persons;
  }else{
     persons= (List<Person>)Session["personslist"];
  }
}

protected void Button1_Click(object sender, EventArgs e){
 persons.Add(new 
 Person(TextBox1.Text,int.parse(TextBox2.Text),TextBox3.Text));
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download