C# tutorial: Entity Framework to display data table in DataGridView

Using Entity Framework to display table of data of SQL Server database in DataGridView

In the previous tutorial about Entity Framework you learned how to create Entity Data Model and use classes generated from the model to work with the database of SQL Server Expression in a Console Application. In this tutorial, you will learn how to get a table of SQL Server Express to display in a DataGridView control by using Entity Framework in Visual Studio C# 2010 Express.

First, you will need to create a Windows Form application. There is a form created automatically for you. Then drag and drop a DataGridView on the form (Form1). This DataGridView will be used to display the Books table of the BookStoreDB database. You will follow the same steps in creating Entity Data Model and connect to the SQL Server Express. If you are new to Entity Framework, please read the Entity Framework tutorial to learn how to create Data Model and connect to SQL Server Express.

Form and DataGridViewe

After creating the Entity Data Model and modify the connection string in App.Config file, you are ready to write C# code to display the Books table in the DataGridView. Now double click the form to display the code window of the form. In the form load procedure, there will be a few lines of code that must be written to bind the Books objects to the DataGridView. Here is the code:

var context=new BookStoreDBEntities();
BindingSource bi = new BindingSource();
bi.DataSource = context.Books;
dataGridView1.DataSource = bi;

C# code to display table of data in DataGridView

By pressing the Start Debugging button (F5) to run the program, you would see the table Books displayed in the DataGridView.

Books table displayed in GridView



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.