c# - Insert Custom value at top of Databound ComboBOX -
i want insert default value @ top of combobox. please tell me proper way so.
what tried
my code:
using (var salaryslipentities = new salary_slipentities()) { employee emp = new employee(); cmbemployeename.datasource = salaryslipentities.employees.tolist(); cmbemployeename.items.insert(0, "select employee"); }
error
items collection cannot modified when datasource property set.
you can using system.reflection. check code sample below.
write common method add default item.
private void additem(ilist list, type type, string valuemember,string displaymember, string displaytext) { //creates instance of specified type //using constructor best matches specified parameters. object obj = activator.createinstance(type); // gets display property information propertyinfo displayproperty = type.getproperty(displaymember); // sets required text display property displayproperty.setvalue(obj, displaytext, null); // gets value property information propertyinfo valueproperty = type.getproperty(valuemember); // sets required value value property valueproperty.setvalue(obj, -1, null); // insert new object on list list.insert(0, obj); }
then use method this.
list<test> tests = new list<test>(); tests.add(new test { id = 1, name = "name 1" }); tests.add(new test { id = 2, name = "name 2" }); tests.add(new test { id = 3, name = "name 3" }); tests.add(new test { id = 4, name = "name 4" }); additem(tests, typeof(test), "id", "name", "< select option >"); combobox1.datasource = tests; combobox1.valuemember = "id"; combobox1.displaymember = "name";
i used test class in code
public class test { public int id { get; set; } public string name { get; set; } }
Comments
Post a Comment