我更新我的問題這個 我創建新類學生C#list.add()的位置覆蓋對象0
class Student
{
private string _firstName;
private string _lastName;
private int _exam1;
private int _exam2;
private int _exam3;
private int _finalExam;
// First Name Property
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
//Last Name Property
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
//Exam 1 Property
public int Exam1
{
get { return _exam1; }
set { _exam1 = value; }
}
// Exam 2 Property
public int Exam2
{
get { return _exam2; }
set { _exam2 = value; }
}
//Exam 3 Property
public int Exam3
{
get { return _exam3; }
set { _exam3 = value; }
}
//Final Exam Property
public int FinalExam
{
get { return _finalExam; }
set { _finalExam = value; }
}
}
}
這是一個方法,我添加新的學生窗體類添加新的學生
public class AddStudent : Form
{
StudentForm stu = null;
public AddStudent()
{
InitializeComponent();
stu = new StudentForm();
stu.Show();
}
private void btnSubmit_Click(object sender, EventArgs e)
{
// split the name into first and last name
string[] name = txtName.Text.Split(',');
Student std = new Student();
std.FirstName = name[0];
std.LastName = name[1];
std.Exam1 = Int32.Parse(txtExam1.Text);
std.Exam2 = Int32.Parse(txtExam2.Text);
std.Exam3 = Int32.Parse(txtExam3.Text);
std.FinalExam = Int32.Parse(txtFinal.Text);
stu.addItem(std);
this.Hide();
}
}
}
,這是它具有列表框中顯示的學生名單我的主要形式
public class StudentForm : Form
{
public StudentForm()
{
InitializeComponent();
}
public List<Student> students = new List<Student>();
public void addItem(Student std)
{
students.Add(std);
// it always show me 1 item in list
MessageBox.Show(students.Count.ToString());
}
}
這部分似乎很奇怪 - 'std.addItem(STD);' - 您要添加的表單項目本身?我懷疑你看到第一項被覆蓋的原因是因爲你每次都創建一個_new_'Student',但是你的類結構使得它很混亂。 –
@DStanley不,它非常有意義。 OP有一個表單,其中包含該表單的列表,OP將創建該表單的一個新實例,並將其自動添加到列表中。這個的目的和最後一句一樣清楚。 –
其實我正在學習c#可以請你說說我的想法嗎? –