C#多个表单打开而不是一个

时间:2013-04-05 01:51:50

标签: c# foreach listbox

我做的是,我创建了许多不同人的实例,然后将每个人添加到名为listOfPeople的列表中,并且我在列表框中命名了每个人。然后我创建了一个新表单来打印出我从列表框中选择的人的详细信息,但是当我选择一个人时,他们的所有细节都以多种形式打开。例如,如果我有Bill& Jill在列表中我和我想查看Bill的详细信息,2个表格将打开,一个显示Bill的详细信息,另一个显示Jill的详细信息。

如何解决此问题,只打开一个表单?

//This is where I create the instance to open the details form for a person
private void detailsButton_Click(object sender, EventArgs e)
{
       if (peopleListBox.SelectedItem == null)
        {
            MessageBox.Show("No person selected!");
        }
        else 
        {                
            foreach (Person person in listOfPeople)
            {
                PersonDetails personDetails = new PersonDetails(person);
                personDetails.Show();
            }
         }
 }


   public partial class PersonDetails : Form
  {
    //This is the constructor that takes in the as a parameter and prints their data
    public PersonDetails(Person person)
    {
        InitializeComponent();
        displayNameLabel.Text = person.PrintData().ToString();
    }
  }

1 个答案:

答案 0 :(得分:1)

假设ListBox中的项目为Person,您只需使用SelectedItem创建一个人。在上面的代码中,foreach循环显式创建并显示列表中每个人的表单。我不太清楚为什么你会被这种行为搞糊涂。

private void detailsButton_Click(object sender, EventArgs e)
{
    if (peopleListBox.SelectedItem == null)
    {
        MessageBox.Show("No person selected!");
    }
    else
    {
        PersonDetails personDetails = 
                        new PersonDetails(peopleListBox.SelectedItem);
        personDetails.Show();
    }
}

如果SelectedItem不是某个人,那么您需要一种方法将SelectedItem映射到listOfPeople中的特定项目。例如,如果SelectedItem是名称的字符串表示形式,listOfPeopleDictionary<string, Person>,那么您可以执行PersonDetails personDetails = listOfPeople[peopleListBox.SelectedItem];

相关问题