我实际上是在添加一个列表;使用for..loop通过列表框迭代这些名称。
然而,一旦我输入姓名/年龄,它就没有显示任何名字;点击添加人并向人展示;什么都没有显示出来。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GUI_TEST_2
{
public partial class Form1 : Form
{
List<Person_List> people = new List<Person_List>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void addPerson_Click(object sender, EventArgs e)
{
string name = addName.Text;
int age = Convert.ToInt32(addAge.Text);
for (int i = 0; i < people.Count(); i++)
{
people[i].addPersonToList(name, age);
}
}
private void showPeople_Click(object sender, EventArgs e)
{
for (int i = 0; i < people.Count(); i++)
{
string name = people[i].showPeople();
peopleListBox.Items.Add("Name: " + name);
}
}
private void peopleListBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GUI_TEST_2
{
class Person_List
{
public List<Person> listOfPeople = new List<Person>();
public Person_List()
{
}
public void addPersonToList(string name, int age)
{
listOfPeople.Add(new Person(name, age));
}
public string showPeople()
{
string name = "";
for (int i = 0; i < listOfPeople.Count(); i++)
{
name = listOfPeople[i].Name;
}
return name;
}
}
}
答案 0 :(得分:0)
在addPerson_Click事件中,你循环遍历列表人员,但是这个列表不包含任何内容,那么你永远不会调用addPersonToList。
尝试使用像:
Person_List people = new Person_List();
private void addPerson_Click(object sender, EventArgs e)
{
string name = addName.Text;
int age = Convert.ToInt32(addAge.Text);
people.addPersonToList(name, age);
}
答案 1 :(得分:-1)
将它们添加到listOfPeople列表后,您必须将它添加到列表框中。将它们添加到listOfPeople并不意味着它们会自动添加到列表框中。据我所知,没有双向约束。
我将如何实施
showPeople(){
listBox1.Items.Clear();
foreach (var ppl in listOfPeople)
{
listBox1.Items.Add(ppl)
}
}