c# - Correctly displaying list items in a combobox and reacting to an item selection -
i have created a list "employeelist" of custom class objects. class called "employee":
public class employee { public string firstname; public string lastname; public string region; public position position; public list<double> goals; public list<double> tests; public double correlation; public employee supervisor; .... }
here pass list form.cs , bind list combobox
var employeelist = correlation.computecorrelation(); var bsource = new bindingsource(); bsource.datasource = employeelist; combobox1.datasource = bsource.datasource; employee f = (employee)combobox1.selecteditem;
honestly, haven't figured out how whole binding thing works it's not issue.the thing is, once binding done, items appear in combobox default names correlation_new.employee. want display item field "name" employee class. how do that?
also, can't figure out how handle event of selecting item in combobox. need contents of item.
your employee.cs class should written below:
using system; using system.collections.generic; using system.linq; using system.text; namespace yourprojectname { public class employee { public string firstname; public string lastname; public string region; public position position; public list<double> goals; public list<double> tests; public double correlation; public employee supervisor; public string getfirstname() { return firstname; } public string getlastname() { return lastname; } public string getregion() { return region; } /*you can increase method connect variables.*/ } */*above class .net mvc model classes.*/* using system; using system.collections.generic; using system.componentmodel; using system.linq; using system.text; namespace yourprojectname { public partial class form { private list<employee> employees{ get; set; } private void combobox1_selectedindexchanged(object sender, eventargs e) { txttitlebox.text = combobox1.selecteditem.tostring(); } public list<employee> loadcombobox() { list<employee> employees= new list<employee>(); var employeelist = correlation.computecorrelation(); var bsource = new bindingsource(); bsource.datasource = employeelist; employees.add(bsource.datasource); return employees; } private void loadyourcombobox_1(object sender, eventargs e) { employees= loadcombobox(); foreach (employee employee in employees) { combobox1.items.add(employees.getfirstname()); } } } }
when user selects item u can use below code block:
employees employee = employees.where(f => f.getfirstname().equals(combobox1.selectedvalue)).fistordefault(); if (employee!= null) { //do work }
or u can use below code block:
if want firstname: combobox1.selectedvalue if want index: combobox1.selectedindex
i hope codes you.
Comments
Post a Comment