foreach - C# mutilple forms open instead of one -
what did was, created number of instances of different people , added each person list called listofpeople , have each person's named in listbox. created new form print out details of person select listbox, when select 1 person, of details open in multiple forms. example if have bill & jill in listofpeople , view details bill, 2 forms open up, 1 showing details bill , other jill.
how can fix 1 form opens?
//this create instance open details form 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 constructor takes in parameter , prints data public persondetails(person person) { initializecomponent(); displaynamelabel.text = person.printdata().tostring(); } }
assuming items in listbox person
s, need use selecteditem
create single person. in code above, foreach loop explicitly creates , shows form each person in list. i'm not quite sure why confused behavior.
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(); } }
if selecteditem
isn't person, need way map selecteditem
particular item in listofpeople
. instance, if selecteditem
string representation of name, , listofpeople
dictionary<string, person>
, persondetails persondetails = listofpeople[peoplelistbox.selecteditem];
.
Comments
Post a Comment