ProgrammingRookie
ProgrammingRookie

Reputation: 191

How do you change the value of a variable in an instance in windows form

I have an instance of an object which is added to a list and then the data is displayed in a windows form c#. Is it possible to change the data of the instance through the windows form?

Person Joe = new Person("Sam", "Smith", "12.05.1992");
person.Add(Joe);

This is the instance of the person then added to a person list.

textBox1.Text = person.Forename;
textBox2.Text = person.Surname;
textBox4.Text = person.DateOfBirth;

This is how I am displaying it in the form through text boxes so that you can input a new name and subsequently save the changed data.

This was my thought..

person.Forename = textBox1.Text;

but think I need something after it.

Upvotes: 0

Views: 932

Answers (2)

Corak
Corak

Reputation: 2778

Okay, I understand your Person class looks something like this:

public class Person
{
    public Person(string forename, string surname, string dateOfBirth)
    {
        Forename = forename;
        Surname = surname;
        DateOfBirth = dateOfBirth;
    }
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string DateOfBirth { get; set; }

    public override string ToString()
    {
        return Forename + ";" + Surname + ";" + DateOfBirth;
    }
}

So your Form should look like that:

public partial class frmMain : Form
{
    private List<Person> Persons = new List<Person>();

    public frmMain()
    {
        InitializeComponent();

        Person Joe = new Person("Sam", "Smith", "12.05.1992");
        Persons.Add(Joe);

        textBox1.Text = Persons[0].Forename;
        textBox2.Text = Persons[0].Surname;
        textBox3.Text = Persons[0].DateOfBirth;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(Persons[0].ToString()); // before change
        Persons[0].Forename = textBox1.Text;
        MessageBox.Show(Persons[0].ToString()); // after change
    }
}

But I don't quite get, why you would want a List<Person> and not just one Person. If you have more than one Person in the List, how do you know, which one to display and subsequently change?

PS: I would strongly advise you to use DateTime as the Type of your DateOfBirth. You'll be in a world of trouble if you ever want to actually work with the date of birth...

Upvotes: 1

Thunder
Thunder

Reputation: 10986

Tyr text changed event or text validated event eg:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            person.Forename = textBox1.Text;
        }

Upvotes: 0

Related Questions