In this article I will explain with an example, how to bind (populate) ComboBox using Entity Framework in Windows Forms (WinForms) Application using C# and VB.Net.
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Form Design
The Form consists of a ComboBox control and a Button. The Button has been assigned Click event handler.
Bind (Populate) ComboBox from Database using Entity Framework
Inside the Form Load event, the records from the database are fetched using Entity Framework and are selected into a Generic List Collection using LINQ.
Then a new item is inserted in First position into the Generic List Collection which will act as the Default (Blank) item for the ComboBox.
Finally, the Generic List Collection is assigned as the DataSource for the ComboBox.
C#
private void Form1_Load(object sender, EventArgs e)
{
//Fetch the records from Table using Entity Framework.
NorthwindEntities entities = new NorthwindEntities();
List<Customer> customers = (from customer in entities.Customers
select customer).Take(4).ToList();
//Insert the Default Item to List.
customers.Insert(0, new Customer { CustomerID = "0",
ContactName = "Please select" });
//Assign Entity as DataSource.
cbCustomers.DataSource = customers;
cbCustomers.DisplayMember = "ContactName";
cbCustomers.ValueMember = "CustomerID";
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Fetch the records from Table using Entity Framework.
Dim entities As NorthwindEntities = New NorthwindEntities()
Dim customers As List(Of Customer) = (From customer In entities.Customers _
Select customer).Take(4).ToList()
'Insert the Default Item to List.
customers.Insert(0, New Customer With {
.CustomerID = "0",
.ContactName = "Please select"
})
'Assign Entity as DataSource.
cbCustomers.DataSource = customers
cbCustomers.DisplayMember = "ContactName"
cbCustomers.ValueMember = "CustomerID"
End Sub
Fetching the selected Text and Value of ComboBox
When the Submit Button is clicked, the Selected Text and Value of the ComboBox is fetched and displayed using MessageBox.
C#
private void btnSubmit_Click(object sender, EventArgs e)
{
string message = "Name: " + cbCustomers.Text;
message += Environment.NewLine;
message += "CustomerId: " + cbCustomers.SelectedValue;
MessageBox.Show(message);
}
VB.Net
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
Dim message As String = "Name: " & cbCustomers.Text
message += Environment.NewLine
message += "CustomerId: " & cbCustomers.SelectedValue
MessageBox.Show(message)
End Sub
Screenshot
Downloads