Thomas
Thomas

Reputation: 34198

Entity Framework and combo binding in win form apps

i am learning EF. i bind my combo using entity framework. my code was like

SchoolEntities schoolContext = new SchoolEntities();

var departmentQuery = from d in schoolContext.Departments.Include("Courses")
                  orderby d.Name
                  select d;
try
{
    this.cbodepartmentList.DisplayMember = "Name";
    this.cbodepartmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly);
    cbodepartmentList.item.insert(0,"--Select--");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

when i try to add a item after bind the combo then i got error. cbodepartmentList.item.insert(0,"--Select--");

so please tell me someone how to add my own text to combo after bind it. because it is some time required to add text like "--Select--" to combo. please guide with code. thanks

Upvotes: 1

Views: 1048

Answers (1)

Brent Stewart
Brent Stewart

Reputation: 1840

Your problem is that you are trying to add an item to the combobox outside of your DataSource binding. The easy way to handle this is to add your extra items to the collection before binding to the combobox. Something like this:

var departments = schoolContext.Departments.Include("Courses").OrderBy(d => d.Name).ToList();
departments.Insert(0, new Department() { Name = "--Select--" });

try
{    
    this.cbodepartmentList.DisplayMember = "Name";
    this.cbodepartmentList.DataSource = departments;
}
catch (Exception ex)
{    
    MessageBox.Show(ex.Message);
}

Upvotes: 1

Related Questions