简体   繁体   中英

populate listbox from list of objects

I've got Windows form that reads an xml file, stores the data from the xml file to a list of objects. This is the xml file format:

<SalesmanDetails>
    <firstName>as</firstName>
    <surname>s</surname>
    <email>name@example.com</email>
    <dateOfBirth>01/01/1980</dateOfBirth>
    <streetNameAndNumber>23 st </streetNameAndNumber>
    <city>random</city>
    <country>Australia</country>
    <sales>1000</sales>
    <mobilePhoneNumber>+254 123 123 123</mobilePhoneNumber>
    <officeNumber>+65 852 256 5698</officeNumber>
  </SalesmanDetails>

When the user clicks the "View All" button, the firstName and surname of all the people in the xml file should appear on the listbox.

this is the method I have so far:

private void btnViewAll_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            foreach (SalesmanDetails details in salesmanList)
            {
                listBox1.Items.Add(details.firstName +" "+ details.surname);
            }
        }  

When the user double clicks one of the names in the listbox, a messagebox with all the details of that person will be displayed. How would I go about doing this?

You can use String.Format to concatenate the first name and surname while adding ListBoxItem in loop. You can use listbox DoubleClick event to show details by finding the SalesmanDetails on DoubleClick. the following code is sample:

    private void btnViewAll_Click(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
        foreach (SalesmanDetails details in salesmanList)
        {
            listBox1.Items.Add(String.Format("{0} {1}",details.firstName,details.surname));
        }
    }  

    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
         int SalesmanDetailsIndex = listBox1.SelectedIndex;
         SalesmanDetails selectedSalesman=salesmanList[SalesmanDetailsIndex];
         MessageBox.Show(String.Format("{0} {1} email {2}",selectedSalesman.firstName,selectedSalesman.surname,selectedSalesman.email));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM