0

我有一个对象的实例,它被添加到列表中,然后数据以 Windows 窗体 c# 显示。是否可以通过windows窗体更改实例的数据?

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

这是随后添加到人员列表中的人员的实例。

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

这就是我通过文本框在表单中显示它的方式,以便您可以输入新名称并随后保存更改的数据。

这是我的想法。。

person.Forename = textBox1.Text;

但我想我需要一些东西。

4

2 回答 2

1

好的,我知道您的Person课程看起来像这样:

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;
    }
}

所以你的表格应该是这样的:

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
    }
}

但我不太明白,为什么你会想要 aList<Person>而不仅仅是 one Person。如果列表中有多个Person,您怎么知道要显示并随后更改哪一个?

PS:我强烈建议你使用DateTime作为你的DateOfBirth. 如果您想真正使用出生日期,您将陷入困境......

于 2013-04-05T10:40:49.267 回答
0

Tyr 文本更改事件或文本验证事件,例如:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            person.Forename = textBox1.Text;
        }
于 2013-04-05T10:22:52.170 回答