blah blah blah is here! blah blah » Close

up0down
link

Hi all

I'm trying to learn more about arraylist and how to use class.cs files, and I'm really stucked right now and would appreciate some help from you. I have a win form with 2 textboxes and 2 buttons and a few labels. I enter a surname and a lastname in each of the textboxes and click the first button. What I try to achieve is that both names will be collected in an arrayList, and let say I enter 5 different names and then I have a second button when I click that button I want to populate a label with those 5 names from my arrayList. Here is my code from form1.cs:

public void controllButton_Click(object sender, EventArgs e)
{
Person NewPerson = new Person();
NewPerson.lastname = lastNameTextBox.Text;
NewPerson.surname = surNameTextBox.Text;

string sname = NewPerson.surname;
string lname = NewPerson.lastname;

NewPerson.Historian();
}
private void historicButton_Click(object sender, EventArgs e)
{
Person NewPerson2 = new Person();
NewPerson2.Hist();
label1.Text = NewPerson2.lastname;
}


And here is my code from Person.cs:
class Person
{
static ArrayList Historik = new ArrayList();

public string lastname;
public string surname;

public string Lastname
{
get { return this.lastname; }
set { this.lastname= value; }
}
public string Surname
{
get { return this.surname; }
set { this.surname= value; }
}
public void Historian()
{
Historik.Add(lastname);
Historik.Add(surname);
}
public string Hist()
{
foreach (Person s in Historik)
{
return s.lastname;
}
}
}


I hope someone could help me with this, thank you.

last answered 2 years ago

1 answers

up0down
link

Try it like this:

private void controlButton_Click(object sender, EventArgs e)
{
Person NewPerson = new Person();
NewPerson.Lastname = lastNameTextBox.Text;
NewPerson.Surname = surNameTextBox.Text;

NewPerson.Historian();
}

private void historicButton_Click(object sender, EventArgs e)
{
label1.Text = Person.Hist();
}

// ..
// person.cs
// ..
class Person
{
static ArrayList Historik = new ArrayList();

private string lastname; // should be private
private string surname; // ditto

public string Lastname
{
get { return this.lastname; }
set { this.lastname = value; }
}
public string Surname
{
get { return this.surname; }
set { this.surname = value; }
}
public void Historian()
{
Historik.Add(lastname);
Historik.Add(surname);
}
public static string Hist() // should be static
{
string list = "";
for (int i = 0; i < Historik.Count; i += 2)
{
list += (string)Historik[i] + " " + (string)Historik[i + 1] + "\r\n";
}
return list;
}
}

Hi Vulpes, you are great as usual...Thank you very much.

Feedback