2013-04-05 67 views
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; 

,但认为我需要后的东西。

+0

你是什么意思“我需要一些东西”?你的问题到底是什么? – pascalhein 2013-04-05 10:08:07

+0

什么是人?我的意思是,“人”是什么类型?根据你提供的信息,它可能是'List ',或者如果'Student'从某个'Person'类继承了'List ',但是'person.Forename'等没有意义。 – Corak 2013-04-05 10:12:10

+0

表示无法投放 – ProgrammingRookie 2013-04-05 10:12:23

回答

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

但我不明白为什么你w应该想要一个List<Person>而不只是一个Person。如果列表中有多个Person,您如何知道,哪一个显示并随后更改? PS:我强烈建议您使用DateTime作为您的DateOfBirth的类型。如果你想要真正与出生日期一起工作,你将处于一个麻烦的世界......

+0

感谢您认为我需要对我的代码进行一些更改。感谢您的帮助和提示 – ProgrammingRookie 2013-04-05 10:48:17

0

酪氨酸文本改变事件或文本验证事件 如:

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